Ciasto piekarz
Ciasto piekarz

Reputation: 8277

How do I assign a jinja2 variable value to use later in template?

How do I assign a jinja2 variable value to use later in template ?

{% if 'clear' in forcast_list[4] %}
{% img = "sunny.png" %}
{% elif "cloudy" in forcast_list[4] %}
{% img = "sun-cloudy-thunder.png" %}
{% endif %}

<div style="background: right bottom no-repeat url('../static/img/{{img}}')" class="weather-icon-pos">
    <!-- weatehr Icon div -->
</div>

any help would be greatly appreciated.

Upvotes: 11

Views: 29652

Answers (1)

Mangohero1
Mangohero1

Reputation: 1912

Use {% set %}:

{% if 'clear' in forcast_list[4] %}
{% set img = "sunny.png" %}
{% elif "cloudy" in forcast_list[4] %}
{% set img = "sun-cloudy-thunder.png" %}
{% endif %}

More information about assignments in jinja2 here.

Or simply do the conditionals within python and pass the result to jinja2 template:

if 'clear' in forcast_list[4]:
    img = "sunny.png"
elif 'cloudy' in forcast_list[4]:
    img = "sun-cloudy-thunder.png"
...
return render_template('foo.html', img=img)

Upvotes: 18

Related Questions