cammil
cammil

Reputation: 9939

In Jinja2, when should one use macro and when should one use include?

In Jinja2, macros and includes appear to do pretty much the same thing.

e.g.

{% macro input(name, value='', type='text') -%}
    <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">
{%- endmacro %}

{{ input('password', type='password') }} 

-- versus --

{% include 'input.html' %}

input.html file>
<input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">

In order to clarify their uses:

  1. Is there a time when one will work, when the other will not?
  2. If both will work, when should we prefer one over the other?

Upvotes: 9

Views: 2350

Answers (1)

vivekagr
vivekagr

Reputation: 1836

If the goal is to simply include a block of text, then macro and include serve the same goal. But like in your example, macros are much more flexible and can be used to pass parameters and use them.

To answer the question

  1. It isn't strictly the case that one will work where the other doesn't. But includes do take some flexibility out. For example if I wanted to show several different fields of a form using include statement, it'd be hard to do. I'd have to make different template files for each field and include them individually since they can't take in parameters, which'd defeat the purpose.

  2. When you have a chunk of code that you think should be present in a different template just for better organization and it won't need to take any parameters, for example the header, footer, complex navigation menu, etc. then include is good for this case. But when you have something that will be repeated multiple times and might need some dynamic parameters, for e.g. form fields, then you should use macro for it.

Upvotes: 6

Related Questions