图像未出现在 Django 模板 For Loop 中

Images not appearing in Django template For Loop

See Problem Here

我想循环遍历 Django 中的静态图像目录。图像正在正确循环播放,但我的 <img src /> 语法有问题。我在 {{ flag }} 上尝试了很多变体,但无法正常工作。有人可以建议吗?

在 settings.py 中,我创建了以下 STATIC_ROOT 对象:

STATIC_ROOT = '/Users/TheUnforecastedStorm/Desktop/Code_projects/Portfolio_Site/portfolio_site/entrance/static'

在 views.py 中,我将此文件路径加入到我的图像目录中,并将图像列表放入上下文字典中。然后我在回复中包含了这本词典:

import os
from django.conf import settings
from django.shortcuts import render

# Create your views here.
def index(request):
    # Create a dictionary
    context = {}

    # Join images directory to index.html view
    flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/"))  
    context['flags'] = flags
    
    # Return response
    return render(request, "entrance/index.html", context)

然后我在我的模板中遍历这些图像:

<!DOCTYPE html>
{% load static %}
<html>
    <head>
        <link rel="stylesheet" href="{% static 'entrance/entrance.css' %}">
        <script src="{% static 'entrance/entrance.js' %}" type="text/javascript"></script>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>

    <body>
        {% for flag in flags %}
            <img src="{{ flag }}" alt="problem" />
        {% endfor %}
    </body>
</html>

@Mark1 根据我上面的评论,我还没有找到任何东西来证实它,但似乎 {% static %} 模板标签只能采用一个额外的参数来创建路径,所以这是您可以尝试的东西。

在您看来:

def index(request):
    # Create a dictionary
    context = {}

    # Join images directory to index.html view
    flags = os.listdir(os.path.join(settings.STATIC_ROOT, "entrance/images/"))

    # ADD IN THIS LINE HERE
    flags = ['entrance/images/'+fl for fl in flags]


    context['flags'] = flags
    
    # Return response
    return render(request, "entrance/index.html", context)

我添加的行将在您要搜索的目录中的所有文件名的开头添加“entrance/images/”。

然后在您的模板中

{% for flag in flags %}
   <img src="{% static flag %}" alt="problem" />
{% endfor %}

让我知道这是否有效。