将模板字符串传递给Jinja宏

时间:2017-03-01 16:14:24

标签: python flask jinja2

我想从宏中渲染模板字符串。我尝试使用以下使用{{ 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>

1 个答案:

答案 0 :(得分:4)

那是不可能的。

但是,你可以在Jinja宏中使用caller来传递一个块:

{% 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)
) }}