* 1.5.0
+ * removed the need to quote hash keys
* allowed hash keys to be any expression
* added a do tag
* added a flush tag
Literals
~~~~~~~~
+.. versionadded:: 1.5
+ Support for hash keys as names and expressions was added in Twig 1.5.
+
The simplest form of expressions are literals. Literals are representations
for PHP types such as strings, numbers, and arrays. The following literals
exist:
separated by a comma (``,``) and wrapped with squared brackets (``[]``).
* ``{"foo": "bar"}``: Hashes are defined by a list of keys and values
- separated by a comma (``,``) and wrapped with curly braces (``{}``). A value
- can be any valid expression (as of Twig 1.5, keys can also be any valid
- expression).
+ separated by a comma (``,``) and wrapped with curly braces (``{}``):
+
+ .. node-block:: jinja
+
+ # keys as string
+ { 'foo': 'foo', 'bar': 'bar' }
+
+ # keys as names (equivalent to the previous hash) -- as of Twig 1.5
+ { foo: 'foo', bar: 'bar' }
+
+ # keys as integer
+ { 2: 'foo', 4: 'bar' }
+
+ # keys as expressions (the expression must be enclosed into parentheses) -- as of Twig 1.5
+ { (1 + 1): 'foo', (a ~ 'b'): 'bar' }
* ``true`` / ``false``: ``true`` represents the true value, ``false``
represents the false value.
}
$first = false;
- $key = $this->parseExpression();
+ // a hash key can be:
+ //
+ // * a number -- 12
+ // * a string -- 'a'
+ // * a name, which is equivalent to a string -- a
+ // * an expression, which must be enclosed in parentheses -- (1 + 2)
+ if ($stream->test(Twig_Token::STRING_TYPE) || $stream->test(Twig_Token::NAME_TYPE) || $stream->test(Twig_Token::NUMBER_TYPE)) {
+ $token = $stream->next();
+ $key = new Twig_Node_Expression_Constant($token->getValue(), $token->getLine());
+ } elseif ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
+ $key = $this->parseExpression();
+ } else {
+ $current = $stream->getCurrent();
+
+ throw new Twig_Error_Syntax(sprintf('A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "%s" of value "%s"', Twig_Token::typeToEnglish($current->getType(), $current->getLine()), $current->getValue()), $current->getLine());
+ }
+
$stream->expect(Twig_Token::PUNCTUATION_TYPE, ':', 'A hash key must be followed by a colon (:)');
$value = $this->parseExpression();
{{ {0: 1, 'foo': 'bar'}|join(',') }}
{{ {0: 1, 'foo': 'bar'}|keys|join(',') }}
+{{ {0: 1, foo: 'bar'}|join(',') }}
+{{ {0: 1, foo: 'bar'}|keys|join(',') }}
+
{# nested arrays #}
{% set a = [1, 2, [1, 2], {'foo': {'foo': 'bar'}}] %}
{{ a[2]|join(',') }}
{# keys can be any expression #}
{% set a = 1 %}
{% set b = "foo" %}
-{% set ary = { a: 'a', b: 'b', 'c': 'c', a~b: 'd' } %}
+{% set ary = { (a): 'a', (b): 'b', 'c': 'c', (a ~ b): 'd' } %}
{{ ary|keys|join(',') }}
{{ ary|join(',') }}
--DATA--
1,bar
0,foo
+1,bar
+0,foo
+
1,2
bar