[英]Render template from twig extension
我已经构建了一个树枝扩展来做一些事情,其中之一是渲染模板。 如何从树枝扩展内部访问引擎环境并调用 Render 方法?
您可以定义扩展以使其需要环境。 Twig 会自动将它传递给函数。
use Twig\Environment;
use Twig\TwigFunction;
public function getFunctions()
{
return [
new TwigFunction(
'myfunction',
[$this, 'myFunction'],
['needs_environment' => true]
),
];
}
public function myFunction(Environment $environment, string $someParam)
{
// ...
}
public function getFunctions()
{
return array(
new \Twig_SimpleFunction(
'myfunction',
array($this, 'myFunction'),
array('needs_environment' => true)
),
);
}
public function myFunction(\Twig_Environment $environment, string $someParam)
{
// ...
}
使用此函数,用户可以将 twig 环境实例传递给 twig 扩展
private $environment;
public function initRuntime(\Twig_Environment $environment)
{
$this->environment = $environment;
}
@tvlooy 回答给了我一个提示,但对我不起作用。 我需要实现它是:
namespace AppBundle\Twig;
class MenuExtension extends \Twig_Extension
{
public function getName()
{
return 'menu_extension';
}
public function getFunctions()
{
return [
new \Twig_SimpleFunction('myMenu', [$this, 'myMenu'], [
'needs_environment' => true,
'is_safe' => ['html']
])
];
}
public function myMenu(\Twig_Environment $environment)
{
return $environment->render('AppBundle:Menu:main-menu.html.twig');
}
}
我需要额外添加'is_safe' => ['html']
以避免自动转义 HTML。
我还将该课程注册为 symfony 服务:
app.twig.menu_extension:
class: AppBundle\Twig\MenuExtension
public: false
tags:
- { name: twig.extension }
在 TWIG 模板中,我添加了{{ myMenu() }}
我使用"twig/twig": "~1.10"
和 Symfony 3.1.3 版本
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.