Reputation: 9939
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:
Upvotes: 9
Views: 2350
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, macro
s are much more flexible and can be used to pass parameters and use them.
To answer the question
It isn't strictly the case that one will work where the other doesn't. But include
s 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.
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