Problem

Twig allows only hardcoded parameters for the "use" statement. How to dynamically use other twig files?

Example

You want to create different articles on your page. All the sections of your page are based on "pagebase.twig", which contains header and footer. Your articles section uses the template "article.twig", which extends "pagebase.twig". Now you want to create a third layer of twig templates which are holding the actual article data. Multiple inheritance isn't possible in twig, so you are left to the "use" statement. But that can't be used dynamicly to point to the desired article.

Solution

Well, actually there are two solutions. One approach is to put a placeholder in your use statement, for example:

{% use "[MYPLACEHOLDER]" %}

And then load the template, replace the placeholder and pass the code to the twig engine. The other approach is to load and parse the blocks of the other twig file and pass them as an array to the template.

Discussion

You need a function to load and parse the blocks of a twig file to an php array:

    /**
      * This function loads a twig file, parses it and returns an array containing the included blocks.
      * @param string $template_file
      * @return array
      */
     function parse_twig_blocks($template_file){
         $content = file_get_contents($template_file);
         $matches = array();
         preg_match_all('#{% ?block (.+?) ?%}(.*?){% ?endblock ?%}#ms', $content, $matches);
         return array_combine($matches[1], $matches[2]);
     }

If for example you have a twig file "article-312.twig" that you want to load, just call:

 $blocks = parse_twig_blocks('this/is/my/path/article-312.twig"); and all contained blocks are loaded into the array. Now when you render your article template, pass the array to the render function:
 $twig->render('article.twig', array('article' => $blocks)); If the "article-312.twig" file contained blocks like "title" or "content", you can easily access them now in your "article.twig" template:
      <h1>{{article.title}}</h1>
      <div>
         {{article.content|raw}}
      </div>

References