Home > Software engineering >  Using jinja2 between quotation marks / setting inline styles with jinja2
Using jinja2 between quotation marks / setting inline styles with jinja2

Time:03-20

Im using Flask and I want a template to render an array of items.

So far everything works out, but the items have a color property, which I would like to set as the background-color.

I thought that I could simple use the inline style for every element I render in the jinja-loop, but I don't find a solution to get if working in a string:

{%for i in items%}
    <div  style="background: '{{ i.color if i.color is not none else '#000' }}';" onclick="itemClicked(this)" index="{{ loop.index }}"> ... </div>
{%endfor%} 

Is there a way to get this done?

Thanks in advance!

Edit:

I got it to work with following adaption:

<div ... style="{{ 'background: '   data[i][k] if data[i][k] is not none else '#000'   ';' }}">...</div>

Sadly this is marked as an Error in HTML. I guess its not really meant to use it that way, please enlighten me if there is a clean solution! :)

CodePudding user response:

Try this

{%for i in items %}
    <div  {% if i.color %} style="background:{{ i.color}};" {% else %} style="background: #000;" {% endif %} onclick="itemClicked(this)" index="{{ loop.index }}"> ... </div>
{%endfor%} 

  • Related