Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing closure on Twig

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!

like image 716
Carles Avatar asked Sep 25 '22 14:09

Carles


1 Answers

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 ;)

like image 83
Martin Poirier Théorêt Avatar answered Sep 29 '22 15:09

Martin Poirier Théorêt