[Twig] How to use macro and usage example

Macro in Twig tags are functions in ordinary programming languages. It is possible to make reusable elements such as HTML syntax that is used repeatedly.
To put it simply, is it a feeling that html such as buttons that are used repeatedly can be made into a template?

Official: macro – Documentation

How to write a macro

First, how to set the macro.

{% macro basic_button(url, label, marginClass = "mb-3", width = 200) %}
    <a href="{{ url }}" class="btn btn-primary {{ marginClass }}" style="width: {{ width }}px;">
        {{ label }}
{% endmacro %}

It is possible to pass arguments in the same way as programming languages such as PHP.
It is also possible to set the default value by entering the value in advance with =.
You can use the set arguments as variables in the macro, just like regular Twig variables.
Conversely, variables such as callers that are not set as arguments cannot be used in macros.

How to call and use macros

This is how to call the macro that you actually created. In addition to setting in the same Twig file, it is also possible to set only macros in an external file.

How to call a macro in the same Twig

{{ _self.basic_button('/homepage', 'test button') }}

// result
<a href="/homepage" class="btn btn-primary mb-3" style="width: 200;"> test button </a>

Macros in the same file can be accessed using _self.
In the above example, the macro named basic_button created first is called. It’s passing values to the url and label arguments.
Others use the set initial values.

It is possible to give it a different name instead of _self.

// define _self as button
{% import _self as button %}

// call macro
{{ button.basic_button('/homepage', 'test button', 'mb-5', 300) }}


How to call a macro in an external file (import)

If the macro created at the top is defined in a file called button_macro.twig

{% import "button_macro.twig" as button %}

// call macro
{{ button.basic_button('/homepage', 'test button', 'mb-5', 300) }}

It is more convenient to create it as an external file so that the macro itself can be reused in other Twigs.

How to call a macro in an external file (from)

You can call the macro as it is or give it a new name.

{% from 'button_macro.html' import basic_button as basic %}

// call macro
{{ basic('/homepage', 'test button', 'mb-5', 300) }}

In the above sample, the macro basic_button is called with a new name basic.

That’s easy, but I tried to explain the macro.
Unlike include, I think it is good to be able to create with the image of making simple parts. If you use include, you cannot load them all at once, but if you put macros together in one file, you can load multiple macros into Twig at the same time. I think it will be easier to code, so please give it a try.

Leave a Reply 0

Your email address will not be published.

19 − 18 =