如何将 TWIG 输出渲染到变量以供以后使用(symfony2)? [英] How to render TWIG output to a variable for later use (symfony2)?

查看:12
本文介绍了如何将 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_Environmenttemplating.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)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆