]>
Commit | Line | Data |
---|---|---|
4f5b44bd NL |
1 | ``include`` |
2 | =========== | |
3 | ||
4 | .. versionadded:: 1.12 | |
5 | The include function was added in Twig 1.12. | |
6 | ||
7 | The ``include`` function returns the rendered content of a template: | |
8 | ||
9 | .. code-block:: jinja | |
10 | ||
11 | {{ include('template.html') }} | |
12 | {{ include(some_var) }} | |
13 | ||
14 | Included templates have access to the variables of the active context. | |
15 | ||
16 | If you are using the filesystem loader, the templates are looked for in the | |
17 | paths defined by it. | |
18 | ||
19 | The context is passed by default to the template but you can also pass | |
20 | additional 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 | ||
27 | You 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 | ||
40 | And if the expression evaluates to a ``Twig_Template`` object, Twig will use it | |
41 | directly:: | |
42 | ||
43 | // {{ include(template) }} | |
44 | ||
45 | $template = $twig->loadTemplate('some_template.twig'); | |
46 | ||
47 | $twig->loadTemplate('template.twig')->display(array('template' => $template)); | |
48 | ||
49 | When you set the ``ignore_missing`` flag, Twig will return an empty string if | |
50 | the template does not exist: | |
51 | ||
52 | .. code-block:: jinja | |
53 | ||
54 | {{ include('sidebar.html', ignore_missing = true) }} | |
55 | ||
56 | You can also provide a list of templates that are checked for existence before | |
57 | inclusion. The first template that exists will be rendered: | |
58 | ||
59 | .. code-block:: jinja | |
60 | ||
61 | {{ include(['page_detailed.html', 'page.html']) }} | |
62 | ||
63 | If ``ignore_missing`` is set, it will fall back to rendering nothing if none | |
64 | of the templates exist, otherwise it will throw an exception. | |
65 | ||
66 | When including a template created by an end user, you should consider | |
67 | sandboxing it: | |
68 | ||
69 | .. code-block:: jinja | |
70 | ||
71 | {{ include('page.html', sandboxed = true) }} | |
72 | ||
73 | Arguments | |
74 | --------- | |
75 | ||
76 | * ``template``: The template to render | |
77 | * ``variables``: The variables to pass to the template | |
78 | * ``with_context``: Whether to pass the current context variables or not | |
79 | * ``ignore_missing``: Whether to ignore missing templates or not | |
80 | * ``sandboxed``: Whether to sandbox the template or not |