在 Twig 中打印包含需要依次打印的子变量的变量
Print variable in Twig containing sub-variables which need to be printed in turn
我在 Symfony 4 中有一个复杂的内容生成系统,它需要渲染一个 Twig 模板。简而言之,有一个允许管理员用户编写模板的 CMS。
例如管理员可以使用所见即所得的编辑器创建页面
<h1>Admin Content</h1>
<p> {{ variable1 }}</p>
Controller 然后会调用 Twig 的 render 方法。
$templateParameters = [
'content' => $this->content, // this is obtained directly from the content that the Admin saved in the database (e.g. see html content above)
'variable1' => 'Test',
'anotherVariable' => 100.00 // in this scenario this variable will not be used
];
return $this->container->get('twig')->render(
sprintf('@pages/%s', $this->templateFilename()), // the twig file name
$templateParameters
);
最后,在 Twig 模板文件中将有一个标签
<div class="content">
{{ content|raw }}
</div>
但是,这样做的问题是显示的内容将与数据库中持久保存的内容完全相同(由管理员输入)。
例如模板将呈现为
<div class="content">
<h1>Admin Content</h1>
<p> {{ variable1 }}</p>
</div>
那么,如何才能将嵌套变量替换为上下文参数数组?这在 Twig 中是否可行,或者我应该在 Controller/Services 中编写某种正则表达式来解析此处的内容? (如果是这样,我可以使用 Twig 的方法(例如渲染)吗?
您可以通过这种方式呈现字符串模板
<?php
$loader = new \Twig\Loader\ArrayLoader([
'content.html' => $this->content,
]);
$twig = new \Twig\Environment($loader);
$renderizedContent = $twig->render('content.html', ['variable1' => 'My value']);
return $this->render("my_real_template.html.twig", [ 'content' => $renderizedContent ]);
在此处查看更多文档https://twig.symfony.com/doc/2.x/api.html#twig-loader-arrayloader
我在 Symfony 4 中有一个复杂的内容生成系统,它需要渲染一个 Twig 模板。简而言之,有一个允许管理员用户编写模板的 CMS。
例如管理员可以使用所见即所得的编辑器创建页面
<h1>Admin Content</h1>
<p> {{ variable1 }}</p>
Controller 然后会调用 Twig 的 render 方法。
$templateParameters = [
'content' => $this->content, // this is obtained directly from the content that the Admin saved in the database (e.g. see html content above)
'variable1' => 'Test',
'anotherVariable' => 100.00 // in this scenario this variable will not be used
];
return $this->container->get('twig')->render(
sprintf('@pages/%s', $this->templateFilename()), // the twig file name
$templateParameters
);
最后,在 Twig 模板文件中将有一个标签
<div class="content">
{{ content|raw }}
</div>
但是,这样做的问题是显示的内容将与数据库中持久保存的内容完全相同(由管理员输入)。
例如模板将呈现为
<div class="content">
<h1>Admin Content</h1>
<p> {{ variable1 }}</p>
</div>
那么,如何才能将嵌套变量替换为上下文参数数组?这在 Twig 中是否可行,或者我应该在 Controller/Services 中编写某种正则表达式来解析此处的内容? (如果是这样,我可以使用 Twig 的方法(例如渲染)吗?
您可以通过这种方式呈现字符串模板
<?php
$loader = new \Twig\Loader\ArrayLoader([
'content.html' => $this->content,
]);
$twig = new \Twig\Environment($loader);
$renderizedContent = $twig->render('content.html', ['variable1' => 'My value']);
return $this->render("my_real_template.html.twig", [ 'content' => $renderizedContent ]);
在此处查看更多文档https://twig.symfony.com/doc/2.x/api.html#twig-loader-arrayloader