apostrophe icon indicating copy to clipboard operation
apostrophe copied to clipboard

Must use import, not include, to define macros

Open boutell opened this issue 11 years ago • 2 comments

We've been defining our macros in separate .html files, which is fine, and importing them with {% include %}.

As it turns out, this is wrong, and only worked by chance in Nunjucks 1.0.

According to the docs for jinja (which Nunjucks is based on), you're supposed to use {% import %}, like this:

{% import 'forms.html' as forms %}

Then you write:

{{ forms.select(arguments...) }}

To output a macro called "select" that lives in forms.html.

Note the namespacing.

This is going to be enforced in Nunjucks 2.0 — calling a macro after loading the file with {% include %} just won't work anymore. {% include %} will be strictly for outputting the contents of that file at the point where you call it.

Since this already works in Nunjucks 1.0, we can get started making this transition in 0.6 now.

boutell avatar Jul 05 '15 14:07 boutell

You can also import "with context" to make data passed to the original template visible inside the macros. Otherwise it is not.

boutell avatar Jul 05 '15 14:07 boutell

We're now doing this in 0.6.

jth- avatar Jan 27 '16 15:01 jth-