/usr/share/doc/php-twig/manual/_sources/tags/macro.rst.txt is in php-twig-doc 2.4.6-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | ``macro``
=========
Macros are comparable with functions in regular programming languages. They
are useful to put often used HTML idioms into reusable elements to not repeat
yourself.
Here is a small example of a macro that renders a form element:
.. code-block:: jinja
{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
{% endmacro %}
Macros differ from native PHP functions in a few ways:
* Default argument values are defined by using the ``default`` filter in the
macro body;
* Arguments of a macro are always optional.
* If extra positional arguments are passed to a macro, they end up in the
special ``varargs`` variable as a list of values.
But as with PHP functions, macros don't have access to the current template
variables.
.. tip::
You can pass the whole context as an argument by using the special
``_context`` variable.
Import
------
Macros can be defined in any template, and need to be "imported" before being
used (see the documentation for the :doc:`import<../tags/import>` tag for more
information):
.. code-block:: jinja
{% import "forms.html" as forms %}
The above ``import`` call imports the "forms.html" file (which can contain only
macros, or a template and some macros), and import the functions as items of
the ``forms`` variable.
The macro can then be called at will:
.. code-block:: jinja
<p>{{ forms.input('username') }}</p>
<p>{{ forms.input('password', null, 'password') }}</p>
If macros are defined and used in the same template, you can use the
special ``_self`` variable to import them:
.. code-block:: jinja
{% import _self as forms %}
<p>{{ forms.input('username') }}</p>
When you want to use a macro in another macro from the same file, you need to
import it locally:
.. code-block:: jinja
{% macro input(name, value, type, size) %}
<input type="{{ type|default('text') }}" name="{{ name }}" value="{{ value|e }}" size="{{ size|default(20) }}" />
{% endmacro %}
{% macro wrapped_input(name, value, type, size) %}
{% import _self as forms %}
<div class="field">
{{ forms.input(name, value, type, size) }}
</div>
{% endmacro %}
Named Macro End-Tags
--------------------
Twig allows you to put the name of the macro after the end tag for better
readability:
.. code-block:: jinja
{% macro input() %}
...
{% endmacro input %}
Of course, the name after the ``endmacro`` word must match the macro name.
.. seealso:: :doc:`from<../tags/from>`, :doc:`import<../tags/import>`
|