fbpx

TWIG: include VS embed VS macro

There are various types of code reuse in Twig but, what are the differences between them?
In this article we’ll explore the differences between include, embed and macro.

First of all, some definitions from the documentation:

All these functions let you split, reuse and incorporate your code wherever you want but they serve different purposes.

Include lets you extract part of the template for better readability and reusability. It doesn’t have an isolated scope (by default) so the included template has access to the same variables of the parent one. You can also pass additional variables like this

There’s also a way to isolate the scope of the included template but you have to do it explicit using the keyword “only”

Embed lets you incorporate a template but mostly it allows for block overriding so you can include a template but also customize some parts (called blocks) in it.
Embeded templates have access to the current context but you can also pass additional variables:

Macro can be considered like a function: it takes some values as inputs and shows the resulting template. It has an isolated scope and you must pass the parameters you require as inputs.
You must declare it and then import it where you want to use it.

Madisoft
Madisoft
Articoli: 19

Lascia una risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.