pongo2 icon indicating copy to clipboard operation
pongo2 copied to clipboard

Macros cannot be defined outside the block they are used in

Open nathan-osman opened this issue 7 years ago • 4 comments

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.

nathan-osman avatar Oct 03 '16 07:10 nathan-osman

Hi, has this issue been resolved?

smithaitufe avatar Apr 23 '18 16:04 smithaitufe

I can confirm that it still does not work.

Silentd00m avatar Apr 16 '19 19:04 Silentd00m

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(...) }}.

iredmail avatar May 11 '21 05:05 iredmail

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 macro m1, and defines a block named main:
{% import "macros/form_inputs.html" m1 %}

<html>
    ...
    {% block main %}
    {% endblock %}
</html>
  • File search.html, it imports m2 outside block main (not work), also imports m3 inside block main (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.

iredmail avatar May 11 '21 14:05 iredmail