A Beginner’s Guide to Twig Macros
What Are Twig Macros?
Twig macros are reusable functions within Twig templates. They help streamline your code by reducing repetition and improving maintainability, similar to functions in programming languages.
Defining a Macro
A Twig macro is defined using the {% macro %}
tag. It can take parameters just like a function.
{% macro button(text, url, class) %}
<a href="{{ url }}" class="btn {{ class }}">{{ text }}</a>
{% endmacro %}
This macro creates a button component that can be reused multiple times with different values.
Using Macros in a Template
To use a macro, you need to call it within a Twig template:
{{ _self.button('Click me', 'https://example.com', 'btn-primary') }}
Here, _self
refers to the current file, meaning that the macro is being called from within the same template.
Storing Macros in a Separate File
For better organization, macros can be stored in a separate file (e.g., macros.twig
) and imported when needed.
{% import 'macros.twig' as macros %}
{{ macros.button('Learn More', 'https://example.com', 'btn-secondary') }}
Benefits of Using Twig Macros
- Code Reusability: Avoid duplicating the same structures.
- Improved Readability: Keep templates cleaner and more structured.
- Easy Maintenance: Update macros once and reflect changes everywhere.