Hello.

Recently I started learning Twig, and I don’t understand how to work with child templates (layouts) at all.

How do I send data to a child layout so that after the output of the main layout, the children are displayed with the transferred data. Or is it necessary to build all layouts with data piece by piece and then collect?

Well, here's how, for example, to transfer the menu array to the menu.twig layout :

index.php

/*...CODE...*/ Twig_Autoloader::register(); $loader = new Twig_Loader_Filesystem($twig_filesystem); $twig = new Twig_Environment($loader, array( 'cache' => TWIG_CACHE, 'debug' => TWIG_DEBUG)); 
$twig->display('main.twig', array()); /*...CODE...*/

main.twig

 /*...CODE...*/ {% include "header.twig" %} /*...CODE...*/ 

header.twig

 /*...CODE...*/ {% include "menu.twig" %} /*...CODE...*/ 

menu.twig

 /*...CODE...*/ {% for link in menu %} <li><a href="{{link.href}}">{{ link.name }}</a></li> {% endfor %} /*...CODE...*/ 


Help me please. Thank you in advance!

UPD: at least give links, please)

    2 answers 2

    How difficult is the page you are building. See the Extends section at http://twig.sensiolabs.org/doc/tags/extends.html It's easier to create one master (or a couple) template, inherit from it, and create similar templates by overriding blocks.

    For the variables in include, see http://x-twig.ru/tags/include/ they are passed

     {% include 'template.html' with {'foo': 'bar'} %} 

    Those. transfer variables to the main template, in the main template you specify which variables to transfer to the child when include

    • Well, in principle, since you suggested it is also possible. I just thought that you can transfer data from the controller to the child template. - KRasul
    • twig was a bomb because he had Extends, and now smarty supports it. In general, Extends taxis, especially if the templates are not very different from each other. If, on the contrary, the patterns are very different, but there are some common parts then include - hardworm

    It is very useful to read the documentation . Here is a brief excerpt from it:

     {% include 'template.html' with {'foo': 'bar'} %} {% set vars = {'foo': 'bar'} %} {% include 'template.html' with vars %} 

    Accordingly, variables can be created not only in the template, but also transferred from the script.

    • I do not understand, but how to transfer data from the controller? Send them to the main layout and then distribute them to the subsidiaries? - KRasul
    • @KRasul, $twig->render('main.twig', ['vars' => ['foo' => 'bar']]); . I use render in my projects instead of display . Honestly - I did not read what the difference is. - ArchDemon
    • display it displays the data immediately ( echo is not needed), and you can use render when you need to upload the data to a variable, well, or also output by adding echo . - KRasul
    • And essentially the same thing - KRasul