How to provide variable name, containing image filename, as argument inside 'style' tag of div element?

Viewed 24

I am working on a Flask project, I want to pass in the variable containing the image filename inside the style tag, but I cannot do so. Instead, I have to use multiple if-elif-else statements as shown below.

<td class="d-flex align-items-center">
{% if cert.img_file == "dl_ai.png" %}
    <div class="img" style="background-image: url(../static/dl_ai.png);"></div>
{% elif cert.img_file == "michigan.png" %}
    <div class="img" style="background-image: url(../static/michigan.png);"></div>
{% elif cert.img_file == "meta.png" %}
    <div class="img" style="background-image: url(../static/meta.png);"></div>
{% elif cert.img_file == "john_hopkins.png" %}
    <div class="img" style="background-image: url(../static/john_hopkins.png);"></div>
{% elif cert.img_file == "hong_kong.png" %}
    <div class="img" style="background-image: url(../static/hong_kong.png);"></div>
{% elif cert.img_file == "ibm.png" %}
    <div class="img" style="background-image: url(../static/ibm.png);"></div>
{% else %}
    <div class="img" style="background-image: url(../static/stanford.png);"></div>
{% endif %}
<div class="pl-3">
    <span>{{ cert.name }}</span>
</div>

I have used url_for but it doesn't seem to work or maybe I have used wrong syntax. Can anyone kindly help me out?

1 Answers

You're already expanding cert.name into your HTML, so I don't understand why you can't do the same thing for cert.img_file. Should be just:

<td class="d-flex align-items-center">
<div class="img" style="background-image: url(../static/{{ cert.img_file }});"></div>
<div class="pl-3">
    <span>{{ cert.name }}</span>
</div>
Related