Matt Welander Matt Welander - 4 months ago 17x
PHP Question

How to render TWIG output to a variable for later use (symfony2)?

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} %}
{% endfor %}

...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,

All it gives me at the moment (the contents of $content[$i]['html']) is



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...

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.

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(...));

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.