9

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.

1
  • jinja2 variables are passed from your Flask app. You must specify them in your render_template() code
    – Mangohero1
    Aug 29, 2017 at 15:23

1 Answer 1

15

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)
2
  • 1
    is there no way to set a variable value inside of jinja itself ? Aug 29, 2017 at 15:32
  • @Ciastopiekarz did a little digging. see my updated answer
    – Mangohero1
    Aug 29, 2017 at 15:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.