Macros cannot be defined outside the block they are used in
The following example works:
{% block content %}
{% macro html_test(name) %}
<p>Hello {{ name }}.</p>
{% endmacro %}
{{ html_test("Max") }}
{% endblock %}
The following does not:
{% macro html_test(name) %}
<p>Hello {{ name }}.</p>
{% endmacro %}
{% block content %}
{{ html_test("Max") }}
{% endblock %}
Importing macros outside a block does not work either:
// util.html
{% macro html_test(name) export %}
<p>Hello {{ name }}.</p>
{% endmacro %}
// index.html
{% import "util.html" html_test %}
{% block content %}
{{ html_test("Max") }}
{% endblock %}
Want to back this issue? Post a bounty on it! We accept bounties via Bountysource.
Hi, has this issue been resolved?
I can confirm that it still does not work.
I can confirm that it still does not work.
@flosch Any plan to help fix this 5-year old issue? :)
More details about our usage:
- We usually define (and export) macros in
macros/form_inputs.html, for example:{% macro input_text(...) export %}. - We call the macro in other pongo2 files:
{{ input_text(...) }}.
Here're some examples which works or not, hope it helps avoiding confusions for users coming from Python Jinja2.
- File
macros/form_inputs.html
{% macro m1(...) export %}...{% endmacro %}
{% macro m2(...) export %}...{% endmacro %}
{% macro m3(...) export %}...{% endmacro %}
- File
layout.html, it imports macrom1, and defines a block namedmain:
{% import "macros/form_inputs.html" m1 %}
<html>
...
{% block main %}
{% endblock %}
</html>
- File
search.html, it importsm2outside blockmain(not work), also importsm3inside blockmain(it works):
{% extends "layout.html" %}
{% import "macros/form_inputs.html" m2 %} <!-- imports `m2` outside block `main` -->
{% block main %} <!-- enter block `main` -->
{% import "macros/form_inputs.html" m3 %} <!-- imports `m3` inside block `main` -->
{{ m1(...) }} <!-- It works -->
{{ m2(...) }} <!-- it does NOT work -->
{{ m3(...) }} <!-- It works -->
{% endblock%}
If you come from Jinja2, you may be used to import m2 outside block main, but this does not work in pongo2.