我不理解Jinja2调用块

16 投票
1 回答
7095 浏览
提问于 2025-04-16 11:51

我明白这个概念,但我不太懂具体的写法。

我打算用他们网站上的一个例子

{% macro render_dialog(title, class='dialog') -%}
<div class="{{ class }}">
    <h2>{{ title }}</h2>
    <div class="contents">
        {{ caller() }}
    </div>
</div>
{%- endmacro %}

{% call render_dialog('Hello World') %}
   This is a simple dialog rendered by using a macro and
    a call block.
{% endcall %}

这个代码的输出结果会是什么呢?

还有一个小问题(因为我对这个怎么运作感到非常困惑):每个宏只能有一个调用者吗?

1 个回答

15

这是输出结果:

<div class="dialog">
    <h2>Hello World</h2>
    <div class="contents">

   This is a simple dialog rendered by using a macro and
    a call block.

    </div>
</div>

所以当我们调用 render_dialog 时,传入的标题是 'Hello World'。当代码执行到 caller() 时,它会把 call 块里的内容传递过去。

撰写回答