How to render TWIG output to a variable for later use (symfony2)?(如何将 TWIG 输出渲染到变量以供以后使用(symfony2)?)
问题描述
不要像这样在我的 TWIG 中渲染每张幻灯片(参见第 6 行):
Instead of doing this rendering of each slide in my TWIG like this (see line 6):
{# loop out the slides #}
{% for c in contents %}
{% set i=i+1 %} {# increase slide number #}
<div id="slide{{ i }}" class="slide" style="z-index:{{ i }};">
{# the slide itself, rendered by it's own template #}
{% include 'BizTVArchiveBundle:ContentTemplate:'~c.template~'/view.html.twig' with {'contents': c, 'ordernumber': i} %}
</div>
{% endfor %}
...相反,我想将所有这些逻辑保留在控制器中,以便将一组准备好的幻灯片传递给视图.我该怎么做这样的事情(见第 9 行):
...Instead I would like to keep all of that logic in the controller, to just deliver to the view an array of ready slides. How can I do something like this (see line 9):
//do stuff...
foreach ($container->getContent() as $c) {
$content[$i]['title'] = $c->getTitle();
$content[$i]['sort'] = $c->getSortOrder();
$content[$i]['data'] = $c->getData();
$content[$i]['template'] = $c->getTemplate()->getId();
$content[$i]['duration'] = $this->extract_seconds($c);
$content[$i]['html'] = $this->render('BizTVArchiveBundle:ContentTemplate:'.$content[$i]['template'].'/view.html.twig', array(
'contents'=> $content[$i],
'ordernumber' => 99,
));
}
目前它给我的只是($content[$i]['html']的内容)是
All it gives me at the moment (the contents of $content[$i]['html']) is
{"headers":{}}
推荐答案
最好include模板中的模板,这样您就可以将模板渲染保留在视图层中,并将逻辑保留在控制器层中.
It's better if you include the template in the template, this way you keep the templating rendering in the view layer and the logic in the controller layer.
不过,如果你真的想要的话……
But well, if you really want it...
您可以使用 2 个服务来做到这一点:twig
正在使用 Twig_Environment
或 templating.engine.twig
,这是一个模板层构建在 Symfony2 for Twig 中,这可以很容易地切换到 templating.engine.php
.
You can use 2 services to do that: twig
is using the Twig_Environment
or templating.engine.twig
which is a templating layer build in Symfony2 for Twig, this can be easily switched ot templating.engine.php
.
如果您使用 twig
服务,您可以查看 twig 文档使用方法:
If you use the twig
service, you can see the twig docs on how to use it:
$template = $this->get('twig')->render('/full/path/to/Resources/views/'.$content[$i]['template'].'/view.html.twig', array(...));
如果您使用 templating.engine.twig
服务,请参阅 模板关于如何使用它的文档,与Twig_Environment
几乎完全相同.
If you use the templating.engine.twig
service, see the templating docs on how to use it, which is almost exact the same as the Twig_Environment
.
这篇关于如何将 TWIG 输出渲染到变量以供以后使用(symfony2)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何将 TWIG 输出渲染到变量以供以后使用(symfony2)?


基础教程推荐
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- 如何替换eregi() 2022-01-01