gpt4 book ai didi

python - 将模板字符串传递给 Jinja 宏

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:57 25 4
gpt4 key购买 nike

我想从宏中渲染模板字符串。我尝试使用以下使用 {{ comment|safe }} 呈现模板的宏来完成此操作,但呈现了模板中的变量,例如 {{ name }}从字面上代替 name 的值。如何在宏参数中允许变量数据?

{% macro comment_el(image_url, name, comment) %}
<div class="media no-border-top">
<div class="media-left">
<a href="{{ outgoing_url }}" >
<img class="media-object" src="{{ image_url }}" />
</a>
</div>
<div class="media-body">
<h4 class="media-heading"><a href="{{ outgoing_url }}" >{{ name }}</a></h4>
<p>{{ comment|safe }}</p>
</div>
</div>
{% endmacro %}
{{ comment_el(
url_for("static", filename="img/c01.jpg"),
"Some Name",
"This comment is amazing. All I want to say is that {{ name }} is an amazing person"
) }}

输出:

<p>This comment is amazing. All I want to say is that {{ name }} is an amazing person</p>

最佳答案

那是不可能的。

但是,您可以在 Jinja 宏中有一个 caller 来让您传递一个 block :

{% macro comment_el(image_url, name) %}
...
<div class="media-body">
<p>{{ caller() }}</p>
</div>
...
{% endmacro %}

然后这样调用它:

{% call comment_el(url_for("static", filename="img/c01.jpg"), "Some Name") -%}
This comment is amazing. All I want to say is that {{ name }} is an amazing person
{%- endcall %}

相关文档:http://jinja.pocoo.org/docs/2.9/templates/#call


解决它的另一种选择是:

{% set comment -%}
This comment is amazing. All I want to say is that {{ name }} is an amazing person
{%- endset %}
{{ comment_el(url_for("static", filename="img/c01.jpg"),
"Some Name",
comment
) }}

相关文档:http://jinja.pocoo.org/docs/2.9/templates/#block-assignments


为了完整起见,您还可以使用格式化:

{{ comment_el(url_for("static", filename="img/c01.jpg"),
"Some Name",
"This comment is amazing. All I want to say is that %s is an amazing person" | format(name)
) }}

关于python - 将模板字符串传递给 Jinja 宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42536716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com