user1766080 user1766080 - 14 days ago 5
Twig Question

Twig access object

i want to access the value of a object inside a twig template.

Normally i would get the return like that:

echo $lang->get("test");


But how can i do the same in the template with twig?

I tried so many methods but no one worked.

For example i tried:

{{ attribute(lang, get, 'test') }}


with the result


Catchable fatal error: Argument 3 passed to
Twig_Node_Expression_GetAttr::__construct() must be an instance of
Twig_Node_Expression_Array, instance of Twig_Node_Expression_Constant
given


thanks

Answer

What you're trying to do is call a method on an object with parameters in a Twig template. I do not think this is supported, as it's probably viewed as a bad idea. Twig supports the notion of getters on an object though, which are called without parameters:

{{ lang.test }}

will try to invoke one of the following, in this order:

  • $lang->test
  • $lang->test()
  • $lang->getTest()
  • $lang->isTest()

If the object implements any of these accessors and conventions, Twig will find it. Anything outside of this convention, like get('test'), is not part of the Twig philosophy. And it's not a widely used idiom in general, so you should probably stick to one of the above methods.

See http://twig.sensiolabs.org/doc/templates.html#variables.

You can implement __isset, __get or __call magic methods to support one of these accessor methods.

Comments