【问题标题】:How to load images in a for loop in django template?如何在 django 模板的 for 循环中加载图像?
【发布时间】:2020-01-23 06:42:54
【问题描述】:

对于名称生成器,我想显示字母表(如可点击的图像)以过滤初始值,但在 for 循环中加载图像时遇到问题。

这里有两个暂定在我的.html

  {% for letter in initials %}
    <a href="#" onclick="FilterByInitial()"><img width='32' height='32' src="{% static 'lists/icons/{{ letter }}_grey.ico' %}" alt='{{ letter }}' /></a>

    {% with letter|add:'_grey.ico' as myimage %}
      <a href="#" onclick="FilterByInitial()"><img width='32' height='32' src="{% static 'lists/icons/myimage' %}" alt='{{ letter }}' /></a>
    {% endwith %}
  {% endfor %}

其中 initials 是一个包含所有字母的字符串:

initials = ascii_lowercase

我的 Firefox 中的网络选项卡给出了 myimage{{ letter }}_grey.ico 未找到。该页面显示替换文本。这有效:

src="{% static 'lists/icons/a_grey.ico' %}"

我什至尝试添加|safe,但无济于事

【问题讨论】:

    标签: html django image for-loop django-templates


    【解决方案1】:

    您的方法不起作用,因为未评估字符串中的模板变量。

    试试这个:

    {% with 'lists/icons/'|add:letter|add:'_grey.ico' as myimage %}
      <a href="#" onclick="FilterByInitial()">
        <img width='32' height='32' src="{% static myimage %}" alt='{{ letter }}' />
      </a>
    {% endwith %}
    

    或者,您可以创建一个自定义过滤器,如下所示:

    # templatetags/image_tags.py
    @register.filter
    def image_for_letter(letter):
        return f'lists/icons/{letter}_grey.ico'
    
    
    {% load image_tags %}
    ...
      <a href="#" onclick="FilterByInitial()">
        <img width='32' height='32' src="{% static letter|image_for_letter %}" alt='{{ letter }}' />
      </a>
    {% endwith %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 2013-10-26
      • 2013-06-30
      • 2021-10-17
      • 1970-01-01
      • 2012-07-25
      • 2021-12-26
      • 2014-09-14
      相关资源
      最近更新 更多