我正在尝试循环访问静态/文件夹中的图像。我可以循环遍历主“静态”文件夹中的图像,但是当我将它们放入“静态/文件夹”时,我不确定如何在 html 中执行此操作。
我的 html 行(当 img 在主“静态”文件夹中时有效)
{% for file in files %}
<img src=" {% static file %}" height="800">
<p>File name:{{ file }}</p>
{% endfor %}
我的观点.py
def album1(request):
images = '/home/michal/PycharmProjects/Family/gallery/static/'
files = os.listdir(os.path.join(images))
context = {'files': files}
return render(request, 'gallery/album1/main.html', context)
如果我将 View 更改为:
def album1(request):
images = '/home/michal/PycharmProjects/Family/gallery/static/'
files = os.listdir(os.path.join(images, 'folder'))
context = {'files': files}
return render(request, 'gallery/album1/main.html', context)
它按预期在“static/folder/”中循环文件名,但后来我不知道如何在 html 中更改它,因为它将文件名添加到:/static/{{ file }} 而不是/static/folder/{{ 文件 }}。 我认为我遗漏了某些内容或需要更改此特定页面上的加载静态内容?
{% load static %} # either here
<img src=" {% static file %}"> # or here?
最佳答案
您在文件名前加上文件夹的名称:
from os.path import <b>join</b>
def album1(request):
images = '/home/michal/PycharmProjects/Family/gallery/static/'
files = os.listdir(join(images, 'folder'))
context = {'files': [<b>join(folder, file)</b> for file in files]}
return render(request, 'gallery/album1/main.html', context)
您可以使用 |slice
template filter [Django-doc] 在模板中切片:
{% for file in files<b>|slice:':21'</b> %}
<img src=" {% static file %}" height="800">
<p>File name:{{ file }}</p>
{% endfor %}
但在 View 中执行此操作效率更高,因为您可以通过执行更少的 join
调用来节省周期,而且模板的效率低于 Python 代码。
https://stackoverflow.com/questions/63529260/
相关文章:
node.js - puppeteer overridePermissions 剪贴板读取不适用于
reactjs - Expo React-Native 调试器 - 错误 : Unable to r
python - 如何在python中调整直方图上的字体大小
flutter - 飞镖 :tml and dart:js not found error flut
ios - 快速用户界面 | onDrag - 自定义(dragItem)预览图像外观
node.js - 无法在谷歌云功能中调试 Puppeteer 超时