gpt4 book ai didi

Twig 扩展 : render template with variables

转载 作者:行者123 更新时间:2023-12-05 04:12:49 25 4
gpt4 key购买 nike

我已经创建了一个 twig 扩展来渲染一个带有一些变量的 View ,但是我有这个错误

An exception has been thrown during the rendering of a template ("Notice: Array to string conversion") 
in :Backend\twig:activate.html.twig at line 1.

这是类扩展:

namespace AppBundle\Twig;

class ActivateExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('activate', array($this, 'booleanFilter'), array('is_safe' => array('html'),
'needs_environment' => true)),
);
}

public function booleanFilter(\Twig_Environment $twig, $var1, $var2)
{

return $twig->render(':Backend/twig:activate.html.twig', array(
'var1' => $var1,
'var2' => $var2
));
}

public function getName()
{
return 'activate_extension';
}
}

这是要渲染的 View :

//test
{{ var1 }}<br>
{{ var2 }}

这是过滤器在另一个 View 中的调用方式:

{{ entity.activate|activate('test var1', 'test var2') }}

最佳答案

引用 TWIG 开发者指南关于 Filters :

When called by Twig, the PHP callable receives the left side of the filter (before the pipe |) as the first argument and the extra arguments passed to the filter (within parentheses ()) as extra arguments.

所以 php 函数的第一个参数是 entity.activate 的值,可能是错误数组,然后其他参数作为参数传递。例如,您应该按如下方式更改您的过滤器:

public function booleanFilter(\Twig_Environment $twig, $activate, $var1, $var2)
{

return $twig->render(':Backend/twig:activate.html.twig', array(
'var1' => $var1,
'var2' => $var2
));
}

希望对您有所帮助。抱歉我对 Twig 函数的评论

关于 Twig 扩展 : render template with variables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39347589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com