Support object init from variable

{a} is a shortcut for {a:a}
From ECMAScript 2015 syntax https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Object_initializer
This commit is contained in:
Jérôme TAMARELLE
2020-02-21 14:56:39 +01:00
committed by Fabien Potencier
parent bde54e11b8
commit 133edb3696
3 changed files with 21 additions and 1 deletions
+4
View File
@@ -568,6 +568,10 @@ exist:
{# keys as integer #}
{ 2: 'foo', 4: 'bar' }
{# keys get the variable name when omitted #}
{% set foo = 'foo' %}
{ foo }
{# keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5 #}
{% set foo = 'foo' %}
{ (foo): 'foo', (1 + 1): 'bar', (foo ~ 'b'): 'baz' }
+10 -1
View File
@@ -376,7 +376,16 @@ class ExpressionParser
// * a string -- 'a'
// * a name, which is equivalent to a string -- a
// * an expression, which must be enclosed in parentheses -- (1 + 2)
if (($token = $stream->nextIf(Token::STRING_TYPE)) || ($token = $stream->nextIf(Token::NAME_TYPE)) || $token = $stream->nextIf(Token::NUMBER_TYPE)) {
if ($token = $stream->nextIf(Token::NAME_TYPE)) {
$key = new ConstantExpression($token->getValue(), $token->getLine());
// {a} is a shortcut for {a:a}
if ($stream->test(Token::PUNCTUATION_TYPE, [',', '}'])) {
$value = new NameExpression($key->getAttribute('value'), $key->getTemplateLine());
$node->addElement($value, $key);
continue;
}
} elseif (($token = $stream->nextIf(Token::STRING_TYPE)) || $token = $stream->nextIf(Token::NUMBER_TYPE)) {
$key = new ConstantExpression($token->getValue(), $token->getLine());
} elseif ($stream->test(Token::PUNCTUATION_TYPE, '(')) {
$key = $this->parseExpression();
+7
View File
@@ -83,6 +83,7 @@ class ExpressionParserTest extends \PHPUnit\Framework\TestCase
return [
['{{ [1, "a": "b"] }}'],
['{{ {"a": "b", 2} }}'],
['{{ {"a"} }}'],
];
}
@@ -159,6 +160,12 @@ class ExpressionParserTest extends \PHPUnit\Framework\TestCase
new ConstantExpression('c', 1),
], 1),
],
['{{ {a, b} }}', new ArrayExpression([
new ConstantExpression('a', 1),
new NameExpression('a', 1),
new ConstantExpression('b', 1),
new NameExpression('b', 1),
], 1)]
];
}