Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flask

jinja2

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.

like image 465
Ciasto piekarz Avatar asked Aug 29 '17 15:08

Ciasto piekarz


1 Answers

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)
like image 188
Mangohero1 Avatar answered Sep 27 '22 19:09

Mangohero1