Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig macros VS includes?

I can't really understand the difference between macros and includes in Twig: both seems to do the same stuff, that is take some variables and output something.

What's the difference and why you use macro or include?

like image 335
gremo Avatar asked Oct 03 '11 04:10

gremo


People also ask

Why do we need the only keyword for include or embed?

Based on the differences, Include should be used only when you need to split a template into many functional sub-templates and reuse the wrapped code elsewhere. While Embed is used when you need to customise the reusable templates.

What are macros in Twig?

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."


1 Answers

With includes, you would include an entire template, verbatim. That template would have access to any template variables currently in scope.

With macros, you are defining a kind of function within Twig (not to be confused with a Twig function, which can access other application logic, not just data passed into templates) that can render a particular component given appropriate objects. So you could have a macro for rendering, say, a shopping list which takes a shopping list as a parameter - and you could then reuse this macro without worrying whether you'd passed the data into the template in the same way elsewhere. Variables not explicitly passed into the macro would not be within scope within that macro.

A macro should really do one specific task to take some data and render a reusable component. An include can comprise any chunk of things - it's a lot more up to you. The extensible nature of the way Twig templates work, as opposed to something like Smarty, means that you are likely to use includes less, by design - but there can still be use cases where it will be the easiest way of avoiding duplication in your templates.

like image 81
Douglas Greenshields Avatar answered Sep 20 '22 10:09

Douglas Greenshields