我是 Django 的新手,我想知道实现此目标的最佳方法是什么。
我的静态文件夹中有大量(15K+)图像,我希望在网页上一次显示 3 张图像。
我的尝试:
我可以在模板中对名称进行硬编码,如下所示:
<div id="imageholder">
<img src="{% static "images/im1.jpg" %}" />
<img src="{% static "images/im2.jpg" %}" />
<img src="{% static "images/im3.jpg" %}" />
</div>
但这当然不是 15k+ 图像的选项。我想到了使用 jQuery 来更改函数中的名称。
例如:
<div id="imageholder">
</div>
<script>
names = ['im1','im2','im3']
for (i = 0; i < names.length; i++) {
html = `<img src="{% static "images/${names[i]}" %}" />`
$('#imageholder').append(html)
}
</script>
我相信这会奏效,但它要求我有一个我没有的所有名字的列表。我想也许我可以使用 os.listdir() 但我不知道如何将其放入网页。
请您参考如下方法:
在您的 View 中将列表添加到上下文中:
images = os.listdir("path/to/images") #Can use glob as well
context = {'images': images}
return render(request,'/path/to/template',context}
在模板中:
{% for image in images %}
{% with 'path/to/imagedir/'|add:image as imagePath %}
<img src='{% static imagePath %}' />
{% endwith %}
{% endfor %}
