tweaked macro docs

This commit is contained in:
Fabien Potencier
2019-04-23 08:30:57 +02:00
parent 6e605bf1b5
commit 7446a6d89f
2 changed files with 19 additions and 11 deletions
+15 -7
View File
@@ -2,12 +2,10 @@
==========
Twig supports putting often used code into :doc:`macros<../tags/macro>`. These
macros can go into different templates and get imported from there.
macros are defined in regular templates.
There are two ways to import templates. You can import the complete template
into a variable or request specific macros from it.
Imagine we have a helper module that renders forms (called ``forms.html``):
Imagine having a generic helper template that define how to render forms via
macros (called ``forms.html``):
.. code-block:: jinja
@@ -19,8 +17,12 @@ Imagine we have a helper module that renders forms (called ``forms.html``):
<textarea name="{{ name }}" rows="{{ rows|default(10) }}" cols="{{ cols|default(40) }}">{{ value|e }}</textarea>
{% endmacro %}
The easiest and most flexible is importing the whole module into a variable.
That way you can access the attributes:
There are two ways to import macros. You can import the complete template
containing the macros into a local variable or only import specific macros from
the template.
The easiest and most flexible is importing the whole module into a local
variable:
.. code-block:: jinja
@@ -49,6 +51,12 @@ namespace:
</dl>
<p>{{ textarea('comment') }}</p>
.. note::
Importing macros using ``import`` or ``from`` is **local** to the current
file. The imported macros are not available in included templates or child
templates; you need to explicitely re-import macros in each file.
.. tip::
To import macros from the current file, use the special ``_self`` variable
+4 -4
View File
@@ -60,9 +60,9 @@ information):
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 ``forms`` local variable.
The macro can then be called at will:
The macro can then be called at will in the current template:
.. code-block:: jinja
@@ -81,8 +81,8 @@ special ``_self`` variable to import them:
.. warning::
When you define a macro in the template where you are going to use it, you
might be tempted to call the macro directly via ``_self.input()`` instead
of importing it; even if seems to work, this is just a side-effect of the
might be tempted to call the macro directly via ``_self.input()`` instead of
importing it; even if it seems to work, this is just a side-effect of the
current implementation and it won't work anymore in Twig 2.x.
When you want to use a macro in another macro from the same file, you need to