1``include`` 2=========== 3 4.. versionadded:: 1.12 5 The ``include`` function was added in Twig 1.12. 6 7The ``include`` function returns the rendered content of a template: 8 9.. code-block:: jinja 10 11 {{ include('template.html') }} 12 {{ include(some_var) }} 13 14Included templates have access to the variables of the active context. 15 16If you are using the filesystem loader, the templates are looked for in the 17paths defined by it. 18 19The context is passed by default to the template but you can also pass 20additional variables: 21 22.. code-block:: jinja 23 24 {# template.html will have access to the variables from the current context and the additional ones provided #} 25 {{ include('template.html', {foo: 'bar'}) }} 26 27You can disable access to the context by setting ``with_context`` to 28``false``: 29 30.. code-block:: jinja 31 32 {# only the foo variable will be accessible #} 33 {{ include('template.html', {foo: 'bar'}, with_context = false) }} 34 35.. code-block:: jinja 36 37 {# no variables will be accessible #} 38 {{ include('template.html', with_context = false) }} 39 40And if the expression evaluates to a ``\Twig\Template`` or a 41``\Twig\TemplateWrapper`` instance, Twig will use it directly:: 42 43 // {{ include(template) }} 44 45 // deprecated as of Twig 1.28 46 $template = $twig->loadTemplate('some_template.twig'); 47 48 // as of Twig 1.28 49 $template = $twig->load('some_template.twig'); 50 51 $twig->display('template.twig', ['template' => $template]); 52 53When you set the ``ignore_missing`` flag, Twig will return an empty string if 54the template does not exist: 55 56.. code-block:: jinja 57 58 {{ include('sidebar.html', ignore_missing = true) }} 59 60You can also provide a list of templates that are checked for existence before 61inclusion. The first template that exists will be rendered: 62 63.. code-block:: jinja 64 65 {{ include(['page_detailed.html', 'page.html']) }} 66 67If ``ignore_missing`` is set, it will fall back to rendering nothing if none 68of the templates exist, otherwise it will throw an exception. 69 70When including a template created by an end user, you should consider 71sandboxing it: 72 73.. code-block:: jinja 74 75 {{ include('page.html', sandboxed = true) }} 76 77Arguments 78--------- 79 80* ``template``: The template to render 81* ``variables``: The variables to pass to the template 82* ``with_context``: Whether to pass the current context variables or not 83* ``ignore_missing``: Whether to ignore missing templates or not 84* ``sandboxed``: Whether to sandbox the template or not 85