I'm trying to execute a closure that resides inside an array on a Twig template. Below you could find a simplified snippet of which I'm trying:
//Symfony controller
...
$funcs = array(
"conditional" => function($obj){
return $obj->getFoo() === $obj::TRUE_FOO
}
);
$this->render('template_name', array('funcs' => $funcs));
{# Twig template #}
{# obj var is set #}
...
{% if funcs.conditional(obj)%}
<p>Got it</p>
{% endif %}
When Twig renders the template, throws an exception complaining about an Array to string conversion
An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") in "template_name.html.twig".
500 Internal Server Error - Twig_Error_Runtime
1 linked Exception: ContextErrorException »
I will appreciate your help.
Thanks!
If you are using a closure you can use the the call method of the closure
http://php.net/manual/en/closure.call.php
You will end up with something like this
{{ funcs.conditional.call(obj, obj) }}
Since the first parameter must be the object that 'this' will refer too I am passing the same object as the first parameter.
No twig extension and no extra PHP code to do ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With