Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a template string to a Jinja macro

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>
like image 375
Tinker Avatar asked Mar 01 '17 16:03

Tinker


People also ask

What is Jinja2 macro?

Macros are similar to functions in many programming languages. We use them to encapsulate logic used to perform repeatable actions. Macros can take arguments or be used without them. Inside of macros we can use any of the Jinja features and constructs. Result of running macro is some text.

What is the difference between Jinja and Jinja2?

Jinja, also commonly referred to as "Jinja2" to specify the newest release version, is a Python template engine used to create HTML, XML or other markup formats that are returned to the user via an HTTP response.


1 Answers

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)
) }}
like image 188
ThiefMaster Avatar answered Nov 03 '22 19:11

ThiefMaster