Macros in Twig templates
From the official Twig documentation: “Macros are comparable to functions in regular programming languages. They are useful to put often-used HTML idioms into reusable elements to not repeat yourself.”
{% macro input(name, value, type, size) %} {% endmacro %}
Macros differ from native PHP functions in several ways:
- Default argument values are defined using the default filter inside the macro body.
- Macro arguments are always optional.
- If extra positional arguments are passed to a macro, they go into a special variable called varargs as a list of values.
However, like PHP functions, macros do not have access to the current template variables. You can pass the full context as an argument using the special _context variable.
Calling a Macro
From _self
You can place a macro in the same Twig file from which you are calling it. In that case, use the _self
context...
{{ _self.input(name, value, type, size) }}
From an External File
However, it's recommended to place macros in a separate file (e.g., macros.twig
) so that they can be reused across multiple templates.
For example, in a custom theme called “mytheme,” you would place the macro file here:
[site_root]/themes/custom/mytheme/templates/macros.twig
Note: The macro file can have any name ending in .twig
, but must not have an .html
extension (i.e., macros.html.twig
will not work). The file must also be located in the templates
directory regardless of where it's used (e.g., for Layout Builder templates located in .../mytheme/layouts
, the macro must still reside in ../mytheme/templates
).
In the template where you want to use the macro, add this import statement:
{% import '@mytheme/macros.twig' as myMacros %}
@mytheme
automatically points to the templates
directory of your theme, but you must include any subdirectory structure in the import path, e.g.:
{% import '@mytheme/foo/bar/macros.twig' as myMacros %}
Note that earlier versions of this documentation stated that subdirectory definition wasn't required, so your mileage may vary. If you’re doing this in a custom module, use the same technique—just use the module name instead of the theme name (e.g., @mycustommodule
).
Then use the macro like this:
{{ myMacros.input(name, value, type, size) }}
Examples
In Drupal 8, macros are used to build things like the main navigation (see the menu.html.twig
file).
Drupal’s online documentation is © 2000-2020 by the individual contributors and can be used in accordance with the Creative Commons License, Attribution-ShareAlike 2.0. PHP code is distributed under the GNU General Public License.