

我想遍歷 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>
uj5u.com熱心網友回復:
@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 %}
讓我知道這個是否奏效。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347917.html
