简体   繁体   English

django 循环 static 文件目录

[英]django loop static files directory

Iam trying to loop thru images in static/folder.我正在尝试遍历静态/文件夹中的图像。 I can loop thru images in main 'static' folder but when i put them in 'static/folder' iam not sure how to do it in html.我可以遍历主“静态”文件夹中的图像,但是当我将它们放在“静态/文件夹”中时,我不确定如何在 html 中执行此操作。

my html lines(works when img in main 'static' folder)我的 html 行(当 img 在主“静态”文件夹中时有效)

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

my views.py我的意见.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)

If i change views to:如果我将视图更改为:

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)

It loops filenames in 'static/folder/' as expected, but then i cant figure out how to change it in html,as its adding file names to: /static/{{ file }} instead to /static/folder/{{ file }}.它按预期循环“静态/文件夹/”中的文件名,但后来我不知道如何在 html 中更改它,因为它将文件名添加到:/static/{{file}} 而不是/static/folder/{{文件 }}。 I think iam missing something or something need changing in load static on this particular page?我认为我在这个特定页面上缺少某些东西或需要改变负载 static 的东西?

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

You prepend the filenames with the name of the folder:您在文件名前面加上文件夹的名称:

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)

You can slice in the template with the |slice template filter [Django-doc] :您可以使用|slice模板过滤器 [Django-doc]对模板进行切片:

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

But it is more efficient to do this in the view, since you save cycles on by performing less join calls, and furthermore the templates are less efficient than Python code.但在视图中执行此操作更有效,因为您可以通过执行更少的join调用来节省周期,而且模板的效率低于 Python 代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM