如果文件包含错误,Flask和Jinja for循环跳过

时间:2015-06-26 09:13:04

标签: python flask jinja2

我有一个问题,我试图显示一些拇指。问题是,当我使用变量运行jinja2时,它会显示alt文本,如果拇指包含错误而不是显示替代文本,我宁愿让它跳过或传递。

这是代码

{% block content %}
      {% if games %}
        {% for g in games if g.game_thumb %}
             <img src="static{{ g.game_thumb }}" class="img-rounded" alt="{{ g.game_name }}" width="150" height="150">
        {%endfor%}
    {% endif %}
{% endblock %}

2 个答案:

答案 0 :(得分:0)

I ended up solving this via the flask route via.

from PIL import Image
    try:
        Image.open(thumb).verify()
        print "image"
    except:
        print "failed"
        continue

答案 1 :(得分:0)

Another way and propably more efficient, would be to use image preloading. Pass the src list to javascript through a data attribute or render to a javascript variable. Using javascript you can preload the images and discard the ones that do not load.

You can also simply handle onerror on img which is called when it fails to load, and hide/remove the images.