Macros in Twig Templates

Last updated on
20 December 2016

From the official Twig documentation: "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."

{% 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.You can pass the whole context as an argument by using the special _context variable.

In Drupal 8 a macro is used to create eg. the main navigation (see the menu.html.twig file).