简体   繁体   English

将 twig 代码传递到 twig 模板并渲染它

[英]Passing twig code into a twig template and rendering it

So I have a twig template that's basically empty, and the application generates some twig code and passes this as a variable into a twig template, like this:所以我有一个基本上是空的 twig 模板,应用程序生成一些 twig 代码并将其作为变量传递给 twig 模板,例如:

return $this->render('blank.html.twig', [
    'twig' => $this->generateTwig()
]);

blank.html.twig looks like this:空白.html.twig 看起来像这样:

{{ twig }}

But when the template is rendered it just has un-rendered twig code inside, like this:但是当模板被渲染时,它里面只有未渲染的 twig 代码,如下所示:

{% extends 'base.html.twig' %} {% block content %} <h1>{{ 'app-name'|trans }}...

How do you render the injected twig code in this example?在这个例子中,你如何渲染注入的 twig 代码?

Doing a file_put_contents('blank', $this->generateTwig()) works, but this defeats the purpose of using templates.执行file_put_contents('blank', $this->generateTwig())有效,但这违背了使用模板的目的。

You can solve this two ways.你可以通过两种方式解决。 Either you pre-render $this->generateTwig() 's output and inject (the HTML) into the blank.html.twig template (untested pseudo):您可以预渲染$this->generateTwig()的 output 并将(HTML)注入blank.html.twig模板(伪:未经测试)

$template = $this->get('twig')->createTemplate($this->generateTwig());
$twig = $template->render();

return $this->render('blank.html.twig', [
    'twig' => $twig,
]);

The downside of this approach is that you have to call {{ twig|raw }} in blank.html.twig , otherwise Twig will escape the HTML. The downside of this approach is that you have to call {{ twig|raw }} in blank.html.twig , otherwise Twig will escape the HTML. Also: it feels a bit weird to pre-render a twig template before feeding it to Twig (again).另外:在将 twig 模板提供给 Twig 之前预渲染它感觉有点奇怪(再次)。

The other approach is that you load the template inside of your blank.html.twig template:另一种方法是在空白中加载模板blank.html.twig模板:

{{ include(template_from_string(twig)) }}

The template_from_string function is part of the StringLoaderExtension . template_from_string function 是StringLoaderExtension的一部分。

Docs here: https://twig.symfony.com/doc/3.x/recipes.html#loading-a-template-from-a-string此处的文档: https://twig.symfony.com/doc/3.x/recipes.html#loading-a-template-from-a-string


Edit: Thinking of it, a third approach could be even simpler if blank.html.twig is really just a file that outputs {{ twig }} :编辑:考虑一下,如果空白,第三种方法可能会更简单blank.html.twig实际上只是一个输出{{ twig }}的文件

$template = $this->get('twig')->createTemplate($this->generateTwig());
return $template->render();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM