mirror of
https://github.com/twigphp/Twig.git
synced 2026-09-07 16:06:53 +00:00
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:
committed by
Fabien Potencier
parent
bde54e11b8
commit
133edb3696
@@ -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' }
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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)]
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user