I am trying to display either or ( <img>
or <h1>
) if an image is retrieved from a static URL.
So if this fails to load an image.
{%for team in object_list|slice:":1"%}
<img src="{% static "/img/Teams/" %}{{team.teamname}}.png" class="mx-auto mb-1" alt="{{team.teamname}}">
{%endfor%}
I would like to display a <h1>
and have none of the code above loaded.
{%for team in object_list|slice:":1"%}
<h1>{{team.teamname}}</h1>
{%endfor%}
Im really unsure about the best way to go about resolving this condition. Is it possible to use a
{% if {% static "/img/Teams/" %}{{team.teamname}}.png" %}
or some type of javascript?
Thank you for any input.
You can add a if clause:
{%for team in object_list|slice:":1"%}{% if team.img %}
<img src="{% static "/img/Teams/" %}{{team.teamname}}.png" class="mx-auto mb-1"
alt="{{team.teamname}}">
{% else %}<h1>{{team.teamname}}</h1>{% endif %}
{%endfor%}
So for anyone looking for a possible solution for this problem. This is what i ended up using. A little Jquery to do the job
<script>
$("img").on("error", function() {
var h = document.createElement("H1");
var t = document.createTextNode(this.alt);
h.appendChild(t);
this.replaceWith(h);
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.