* 1.2.0
+ * added the "attribute" function to allow getting dynamic attributes on variables
* added Twig_Loader_Chain
* added Twig_Loader_Array::setTemplate()
* added an optimization for the set tag when used to capture a large chunk of static text
foo[bar]
+.. note::
+
+ If you want to get a dynamic attribute on a variable, use the
+ ``attribute`` function instead.
+
Twig always references the following variables:
* ``_self``: references the current template;
{{ some_date|date(constant('DATE_W3C')) }}
+``attribute``
+~~~~~~~~~~~~~
+
+.. versionadded:: 1.2
+ The ``attribute`` function was added in Twig 1.2.
+
+``attribute`` can be used to access a "dynamic" attribute of a variable:
+
+.. code-block:: jinja
+
+ {{ attribute(object, method) }}
+ {{ attribute(object, method, arguments) }}
+ {{ attribute(array, item) }}
+
+.. note::
+
+ The resolution algorithm is the same as the one used for the ``.``
+ notation, except that the item can be any valid expression.
+
Extensions
----------
return new Twig_Node_Expression_BlockReference($args->getNode(0), false, $line);
}
+ if ('attribute' === $name) {
+ if (count($args) < 2) {
+ throw new Twig_Error_Syntax('The "attribute" function takes at least two arguments (the variable and the attribute)', $line);
+ }
+
+ return new Twig_Node_Expression_GetAttr($args->getNode(0), $args->getNode(1), count($args) > 2 ? $args->getNode(2) : new Twig_Node_Expression_Array(array(), $line), Twig_TemplateInterface::ANY_CALL, $line);
+ }
+
if (null !== $alias = $this->parser->getImportedFunction($name)) {
return new Twig_Node_Expression_GetAttr($alias['node'], new Twig_Node_Expression_Constant($alias['name'], $line), $args, Twig_TemplateInterface::METHOD_CALL, $line);
}
--- /dev/null
+--TEST--
+"attribute" function
+--TEMPLATE--
+{{ attribute(obj, method) }}
+{{ attribute(array, item) }}
+--DATA--
+return array('obj' => new Foo(), 'method' => 'foo', 'array' => array('foo' => 'bar'), 'item' => 'foo')
+--EXPECT--
+foo
+bar