Reputation: 4535
I want to render a template string from a macro. I tried to do it with the following macro that renders the template using {{ comment|safe }}
, but variables in the template such as {{ name }}
are rendered literally instead of with the value of name
. How can I allow variable data in a macro argument?
{% 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"
) }}
Output:
<p>This comment is amazing. All I want to say is that {{ name }} is an amazing person</p>
Upvotes: 8
Views: 7346
Reputation: 318508
That's not possible.
However, you can have a caller
in Jinja macros that lets you pass a block:
{% macro comment_el(image_url, name) %}
...
<div class="media-body">
<p>{{ caller() }}</p>
</div>
...
{% endmacro %}
Then call it like this:
{% 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 %}
Relevant docs: http://jinja.pocoo.org/docs/2.9/templates/#call
Another option to solve it would be this:
{% 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
) }}
Relevant docs: http://jinja.pocoo.org/docs/2.9/templates/#block-assignments
For the sake of completeness, you could also use formatting:
{{ 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)
) }}
Upvotes: 19