Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig render a template inside template

I would like to know how to render a "template inside another template". I have this kind of template :

[...]
{% autoescape false %}
    {{ page.content }}
{% endautoescape %}
[...]

"page.content" can be valued with some twig! For example it can contain some calls like

{{ myObject.poperty }}

or even

{% render "MyBundle:Bundle:myAction" with {'title': myObject.title} %}

By default, the content of page.content is not parsed by Twig. So I have made an extension and I am able to parse calls like {{ page.content }}

My extension looks like :

$loader     = new \Twig_Loader_String();
$this->environment->setLoader($loader);

$template   = $this->environment->loadTemplate($string);
$output     = $template->display(array('myObject' => $object));

But I am still not able to rendre the second kind of call {% render.... %}

I have tried to do :

$stream     = $this->environment->tokenize($string);
$nodes      = $this->environment->parse($stream)->getNode('body')->getNode(0);
$output     = $this->environment->compile($nodes);

But I am stuck...

Do you know how I could render my "page.content" value?

like image 868
Fish Avatar asked Sep 26 '26 05:09

Fish


1 Answers

So I have created a php twig extension, and one solution seems to be :

public function parsingTwig($source, $context)
    {
        $stream     = $this->env->tokenize($source);
        $iterator   = $this->env->parse($stream)->getNode('body')->getIterator();

        while ($iterator->valid())
        {
            $current = $iterator->current();
            $output  = $this->env->compile($current);
            eval($output);
            $iterator->next();
        }
}

You need to define some functions like 'getAttribute' or 'getContext'. These functions can be found in the twi template class...

like image 68
Fish Avatar answered Sep 28 '26 01:09

Fish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!