Wells
Wells

Reputation: 10979

python jinja2: using variable in template with conditional

I have this:

{% for row in data: %}
    <td
            {{'value={{row['value']}}' if 'showit' in map and header in map['showit'] and 'value' in row}}
    > ... </td>
{% endfor %}

But obviously that's not working. Trying to add an HTML attribute to the cell using a secondary column in the row dict. Any thoughts?

Upvotes: 1

Views: 4405

Answers (1)

Jarek Pi&#243;rkowski
Jarek Pi&#243;rkowski

Reputation: 648

Assuming your trouble is with the syntax getting the row['value'], concatenate the strings rather than trying to nest the {{ }}s:

{{ 'value=' + row['value'] if True }}

Replace the True with your condition of course. If you need to quote the param:

{{ 'value="' + row['value'] + '"' if True }}

As @Reza-S4 suggested you can also put the conditional outside the print statement to be a little clearer:

{% if 'showit' in map and header in map['showit'] and 'value' in row: %}
  value="{{ row['value'] }}"
{% endif %}

Upvotes: 1

Related Questions