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