4 Macros are comparable with functions in regular programming languages. They
5 are useful to put often used HTML idioms into reusable elements to not repeat
8 Here is a small example of a macro that renders a form element:
12 {% macro input(name, value, type, size) %}
13 <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
16 Macros differs from native PHP functions in a few ways:
18 * Default argument values are defined by using the ``default`` filter in the
21 * Arguments of a macro are always optional.
23 But as with PHP functions, macros don't have access to the current template
28 You can pass the whole context as an argument by using the special
29 ``_context`` variable.
31 Macros can be defined in any template, and need to be "imported" before being
32 used (see the documentation for the :doc:`import<../tags/import>` tag for more
37 {% import "forms.html" as forms %}
39 The above ``import`` call imports the "forms.html" file (which can contain only
40 macros, or a template and some macros), and import the functions as items of
41 the ``forms`` variable.
43 The macro can then be called at will:
47 <p>{{ forms.input('username') }}</p>
48 <p>{{ forms.input('password', null, 'password') }}</p>
50 If macros are defined and used in the same template, you can use the
51 special ``_self`` variable to import them:
55 {% import _self as forms %}
57 <p>{{ forms.input('username') }}</p>
61 When you define a macro in the template where you are going to use it, you
62 might be tempted to call the macro directly via ``_self.input()`` instead
63 of importing it; even if seems to work, this is just a side-effect of the
64 current implementation and it won't work anymore in Twig 2.x.
66 When you want to use a macro in another macro from the same file, you need to
71 {% macro input(name, value, type, size) %}
72 <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
75 {% macro wrapped_input(name, value, type, size) %}
76 {% import _self as forms %}
79 {{ forms.input(name, value, type, size) }}
83 .. seealso:: :doc:`from<../tags/from>`, :doc:`import<../tags/import>`