Twig: Selecting certain blocks and rendering them

Turns out that one should use $template->renderBlock('blockname', array('test' => 'test')); instead. This will make twig render that block and then return a string containing the markup for that block. One can then use echo to display it or insert it into other templates.

Full example:

$loader = new \Twig_Loader_Filesystem(array('/my-template-root'));
$twig = new \Twig_Environment($loader, array('debug' => true));
$template = $twig->loadTemplate('view\form_div_layout.html.twig');
$result = $template->renderBlock('blockname', array('test' => 'test'));
echo $result;

If you are using Symfony and want to be able to still have access to the global variables (app, app.user, etc) then this works great:

private function renderBlock($template, $block, $params = [])
{
    /** @var \Twig\Environment $twig */
    $twig = $this->get('twig');
    /** @var \Twig\TemplateWrapper $template */
    $template = $twig->load($template);

    return $template->renderBlock($block, $twig->mergeGlobals($params));
}

I just added this has a private function on my controller. Works great. Thanks to @F21 for pointing me in the right direction.

Tags:

Php

Twig

Symfony