Django循环静态文件目录

2024-05-18 08:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试循环浏览静态/文件夹中的图像。我可以循环浏览主“静态”文件夹中的图像,但当我将它们放在“静态/文件夹”中时,我不知道如何在html中进行循环

我的html行(当img在主“静态”文件夹中时工作)

{% for file in files %}
    <img src=" {% static file %}" height="800">
    <p>File name:{{ file }}</p>
{% endfor %}

我的观点

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)

如果我将视图更改为:

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/{{file}}。 我想我在这个页面上缺少了一些东西或者需要在加载静态中更改一些东西

{% load static %}                 # either here 
<img src=" {% static file %}">    # or here?

Tags: 图像文件夹imgosrequesthtmlcontext静态
1条回答
网友
1楼 · 发布于 2024-05-18 08:20:16

在文件名前面加上文件夹名称:

from os.path import join

def album1(request):
    images = '/home/michal/PycharmProjects/Family/gallery/static/'
    files = os.listdir(join(images, 'folder'))
    context = {'files': [join(folder, file) for file in files]}
    return render(request, 'gallery/album1/main.html', context)

您可以使用^{} template filter [Django-doc]在模板中切片:

{% for file in files|slice:':21' %}
    <img src=" {% static file %}" height="800">
    <p>File name:{{ file }}</p>
{% endfor %}

但是在视图中这样做更有效,因为您通过执行更少的join调用来节省周期,而且模板的效率低于Python代码

相关问题 更多 >