Twig macros VS includes?

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.


I am new to Symfony2, but I think the difference between twig macro and include is as following.

include: Used to define common parts in the page, such as header, sidebar or slot.

macro: Used to define functions related to the view, such as pagination.


Even though this question has an accepted answer, I think it is important to point out a few key differences between include and macro in twig.

  1. (The obvious): You can define multiple macros in a single file, resulting in multiple reusable blocks of code per file. An include is always included entirely, so one reusable block of code per file.

  2. There is a significant performance difference between the two options if you are planning to use it inside a loop. From my tests with 10k iterations, here are the times to render the template:

  • raw HTML: 0.0015s
  • macro: 0.040s (27x slower)
  • include: 0.1584s (105x slower)

The macro import was called outside of this iteration.

  1. If you use include '...' with {...}, then you are passing entire context to the included template, and all the context variables (parameters) are optional. With macros, you may define required parameters, which is sometimes handy.

  2. You can define a macro within the same template that calls the macro. Not possible with include.

  3. To use a macro, you will need at least 2 statements in your template: one to import the macro, the other one to use it. Using include is just one statement, which is cleaner.