pythonjinja2templating-engine

How to avoid rendering a block in a base template - or: how to define a multiline block-like variable?


I am rather new to jinja, so please excuse this potentially dumb question ...

I have a jinja macro sitting in a file named lib.jinja which looks as as follows

{% macro some_macro(some_content) %}
    <div class="some_class">{{ some_content }}</div>
{%- endmacro %}

I import it from another file named content.htm, which looks roughly as follows:

{% from "lib.jinja" import some_macro %}
{% block content %}
    Some content
{% endblock %}
{{ some_macro(self.some_macro(self.content())) }}

The rendered output looks as follows:

Some content
<div class="some_class">Some content</div>

Notice that the content appears twice, once rendered through/by the macro, another time - directly above - rendered like it was defined in the block named content in content.htm. I would love to avoid that the block is rendered twice - it is supposed to be fed into the macro and rendered through it only.

I appears that I can "work around" it by turning content.htm into a child template (by adding an extends tag at its top) of an empty base template.

Maybe I have a lack of understanding for the concepts here: A block is not a variable - I get that. If there is no extends tag, the template is treated as a base template, I assume. If there are no child templates or other directives, I guess the block is just rendered as-is and then, for a second time so to speak, picked up by the macro - correct?

How can I solve this in a sane manner, i.e. how could I handle this other than by extending an empty base template? Is there another type of block or variable that would fit my needs?


Solution

  • Just after I submitted this question, I finally found what I was looking for in the manual: Block Assignments.

    {% from "lib.jinja" import some_macro %}
    {% set content %}
        Some content
    {% endset %}
    {{ some_macro(self.some_macro(content)) }}
    

    The set and endset tags solve my problem.