Html 如何在django模板的for循环中加载图像?

Html 如何在django模板的for循环中加载图像?,html,django,image,for-loop,django-templates,Html,Django,Image,For Loop,Django Templates,对于名称生成器,我希望显示字母表(如可单击的图像)以过滤首字母,但在For循环中加载图像时遇到问题 我的.html中有两个选项: {% for letter in initials %} <a href="#" onclick="FilterByInitial()"><img width='32' height='32' src="{% static 'lists/icons/{{ letter }}_grey.ico' %}" alt='{{ letter }}'

对于名称生成器,我希望显示字母表(如可单击的图像)以过滤首字母,但在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 %}
我的firefox中的网络选项卡提供了
myimage
{{letter}}\u grey.ico
未找到。页面显示替换文本。这是有效的:

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

我甚至尝试添加
| safe
,但没有效果

您的方法不起作用,因为字符串中的模板变量没有计算

试试这个:

{% 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 %}
{%with'lists/icons/'| add:letter | add:'u grey.ico'as myimage%}
{%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 %}
#templatetags/image_tags.py
@寄存器过滤器
def图像字母(字母):
返回f'lists/icons/{letter}\u grey.ico'
{%load image_tags%}
...
{%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 %}