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
I know this is an old question, but after 3 hours of scouring the internet and finding no examples, I wanted to make sure it got documented.
Going back to one of your original attempts:
I'm trying to do the same thing, and this should work according to the documentation. Unfortunately, there are no examples of using this. All I found was that the method name (get) had to be a string ('get'), so I changed that, but it still didn't work. What I ended up doing was this:
This worked great, but it's a lot of code to write when I have to do this all over. So I made a simple template with both methods and examined the compiled output. The original was compiled to this:
and the second (2 liner) to this:
After examination, I realized the difference (check the 3rd parameters to getAttribute), the arguments parameter is an array! This is good information to know. I changed my original to this:
and it's now working!
Hope this helps someone!
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:
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.