【发布时间】:2015-12-11 15:05:06
【问题描述】:
我在 views.py 中有一段代码从目录中获取文件名:
def imgArray(request):
filepath = STATIC_PATH+"\\images"
imageArray=[]
ext='.jpg'
for i in os.listdir(filepath):
if(os.path.splitext(i)[1] == ext):
imageArray.append( i )
context = {'imageArray': imageArray}
print context
return render(request, 'imgpage/add_category.html',context)
def add_category(request):
# A HTTP POST?
if request.method == 'POST':
#Do some actions
else:
# If the request was not a POST, display the form to enter details.
imageArray = imgArray(request)
return render(request, 'imgpage/add_category.html')
我想在 javascript 中使用这个图像文件数组。我想使用文件名数组,以便可以使用 js 更改图像源。
print context 语句在 python 控制台中产生以下输出:
{'imageArray': ['image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.
jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg']}
但我根本无法在模板中访问 imageArray。以下是我尝试在模板 html 文件中测试数组是否已通过的脚本:
在 add_category.html 文件中:
{% for img in imageArray %}
<li>{{ img|safe }}</li>
<li>{{ img }}</li>
<p>img</p>
{% endfor %}
另外,请注意<p> 标签内的“img”也不会呈现在屏幕上。
<script type="text/javascript">
var images = "{{imageArray|safe}}";
console.log(images);
console.log("imgx="+images[1]);
document.getElementsByTagName("img")[0].src = DJANGO_STATIC_URL+images[2];
</script>
在上面的脚本中,第一个控制台日志在控制台打印空行,而第二个打印“imgx=undefined”
请建议我可以将 python 列表用作 JS 数组的方法。我使用 Django 1.8.1,但我将托管的服务使用 1.7.x。所以对两者都有效的东西会很棒。
【问题讨论】:
标签: javascript python arrays django templates