在Twig上执行关闭

Car*_*les 5 php closures symfony twig symfony-2.8

我正在尝试执行一个位于Twig模板上的数组内的闭包.您可以在下面找到我正在尝试的简化代码段:


//Symfony controller
...
$funcs = array(
    "conditional" => function($obj){
        return $obj->getFoo() === $obj::TRUE_FOO
    }
);
$this->render('template_name', array('funcs' => $funcs));
Run Code Online (Sandbox Code Playgroud)
{# Twig template #}
{# obj var is set #}
...
{% if funcs.conditional(obj)%}
<p>Got it</p>
{% endif %}
Run Code Online (Sandbox Code Playgroud)

当Twig呈现模板时,抛出一个异常抱怨Array转换为字符串

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 »
Run Code Online (Sandbox Code Playgroud)

我将感谢你的帮助.

谢谢!

Ter*_*oth 1

您不能直接在 Twig 模板内执行闭包。但是,如果您需要在模板中调用一些 PHP,您应该使用创建一个 Twig 扩展并将您的逻辑包含在其中。