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 differ 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 * If extra positional arguments are passed to a macro, they end up in the
24 special ``varargs`` variable as a list of values.
26 But as with PHP functions, macros don't have access to the current template
31 You can pass the whole context as an argument by using the special
32 ``_context`` variable.
37 Macros can be defined in any template, and need to be "imported" before being
38 used (see the documentation for the :doc:`import<../tags/import>` tag for more
43 {% import "forms.html" as forms %}
45 The above ``import`` call imports the "forms.html" file (which can contain only
46 macros, or a template and some macros), and import the functions as items of
47 the ``forms`` variable.
49 The macro can then be called at will:
53 <p>{{ forms.input('username') }}</p>
54 <p>{{ forms.input('password', null, 'password') }}</p>
56 If macros are defined and used in the same template, you can use the
57 special ``_self`` variable to import them:
61 {% import _self as forms %}
63 <p>{{ forms.input('username') }}</p>
67 When you define a macro in the template where you are going to use it, you
68 might be tempted to call the macro directly via ``_self.input()`` instead
69 of importing it; even if seems to work, this is just a side-effect of the
70 current implementation and it won't work anymore in Twig 2.x.
72 When you want to use a macro in another macro from the same file, you need to
77 {% macro input(name, value, type, size) %}
78 <input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
81 {% macro wrapped_input(name, value, type, size) %}
82 {% import _self as forms %}
85 {{ forms.input(name, value, type, size) }}
92 Twig allows you to put the name of the macro after the end tag for better
101 Of course, the name after the ``endmacro`` word must match the macro name.
103 .. seealso:: :doc:`from<../tags/from>`, :doc:`import<../tags/import>`