我正在尝试执行驻留在 Twig 模板上的数组内的闭包。您可以在下面找到我正在尝试的简化片段:
//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 %}
当 Twig 渲染模板时,抛出一个异常,抱怨数组到字符串的转换
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 »
我会感谢你的帮助。
Thanks!
如果您使用闭包,则可以使用闭包的 call 方法
http://php.net/manual/en/closure.call.php
你最终会得到这样的结果
{{ funcs.conditional.call(obj, obj) }}
由于第一个参数必须是“this”也将引用的对象,因此我传递与第一个参数相同的对象。
没有树枝扩展,也没有额外的 PHP 代码要做;)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)