1``import``
2==========
3
4Twig supports putting often used code into :doc:`macros<../tags/macro>`. These
5macros can go into different templates and get imported from there.
6
7There are two ways to import templates. You can import the complete template
8into a variable or request specific macros from it.
9
10Imagine we have a helper module that renders forms (called ``forms.html``):
11
12.. code-block:: jinja
13
14    {% macro input(name, value, type, size) %}
15        <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
16    {% endmacro %}
17
18    {% macro textarea(name, value, rows, cols) %}
19        <textarea name="{{ name }}" rows="{{ rows|default(10) }}" cols="{{ cols|default(40) }}">{{ value|e }}</textarea>
20    {% endmacro %}
21
22The easiest and most flexible is importing the whole module into a variable.
23That way you can access the attributes:
24
25.. code-block:: jinja
26
27    {% import 'forms.html' as forms %}
28
29    <dl>
30        <dt>Username</dt>
31        <dd>{{ forms.input('username') }}</dd>
32        <dt>Password</dt>
33        <dd>{{ forms.input('password', null, 'password') }}</dd>
34    </dl>
35    <p>{{ forms.textarea('comment') }}</p>
36
37Alternatively you can import names from the template into the current
38namespace:
39
40.. code-block:: jinja
41
42    {% from 'forms.html' import input as input_field, textarea %}
43
44    <dl>
45        <dt>Username</dt>
46        <dd>{{ input_field('username') }}</dd>
47        <dt>Password</dt>
48        <dd>{{ input_field('password', '', 'password') }}</dd>
49    </dl>
50    <p>{{ textarea('comment') }}</p>
51
52.. tip::
53
54    To import macros from the current file, use the special ``_self`` variable
55    for the source.
56
57.. seealso:: :doc:`macro<../tags/macro>`, :doc:`from<../tags/from>`
58