Using Macro in Twig Template

Using Macro in Twig Template

- Macros are the Twig version of functions.
- Macros ar same as functions in regular programming languages.
- They are useful to put often used HTML idioms into reusable elements to not repeat yourself.
- You put your skeleton markup in the macro and use parameters passed in to alter that markup and then output it.
Small Example:

{% macro icon_button(title, color, icon_class) %}
<button title="{{ title }}" class="btn btn-{{ color|default('light-green') }}">
     <span class="btn-icon"><i class="fa fa-{{ icon_class }}">
</button>
{% endmacro %}

Macros differ from native programming languages functions in a few ways:
- Arguments of a macro are always optional.
- Default argument values are defined by using the default filter in the macro body.
- If extra positional arguments are passed to a macro, they end up in the special varargs variable as a list of values.
- You can pass the whole context as an argument by using the special _context variable.

To use macro in your project the official Macro in Twig Documentation.