Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

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

{"headers":{}}
like image 618
Matt Welander Avatar asked Jan 06 '14 18:01

Matt Welander


People also ask

What is Twig syntax?

Twig is a template engine for the PHP programming language. Its syntax originates from Jinja and Django templates. It's an open source product licensed under a BSD License and maintained by Fabien Potencier.

What is Twig file extension?

Twig is a PHP template engine. It was created by Symfony developers. Twig files have the extension of . html. twig ; they are a mix of static data such as HTML and Twig constructs.


2 Answers

You can get content form rendered object like this:

$this->render('BizTVArchiveBundle:ContentTemplate:Some.html.twig', array())->getContent();
like image 156
Liutas Avatar answered Oct 18 '22 04:10

Liutas


Within a twig template, you can set the value of a printed variable like this:

{% set rendered %}
  {{ var_to_print }}
{% endset %}
like image 31
joachim Avatar answered Oct 18 '22 04:10

joachim