使用Django 1.8.1中views中的list作为javascript模板中的数组

Using list from views in Django 1.8.1 as an array in javascript template

本文关键字:javascript 数组 作为 中的 Django views 使用 list      更新时间:2023-09-26

我在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。所以,如果能同时兼顾这两方面,那就太好了。

你这里有一个非常奇怪的结构。imageArray()是一个视图,它返回一个完整的HttpResponse;但你从另一个角度来称呼它,add_category。更重要的是,你对结果什么也不做;它被扔掉了,从来没有经过任何地方。因此,很自然地,它在模板中总是空白的。

我不确定你到底在做什么,所以很难知道你到底想要什么。但我怀疑imageArray()应该是一个正常的实用程序方法,它只是返回一个图像列表:

def imgArray():
    filepath = os.path.join(STATIC_PATH, "''images")
    images =[f for f in os.listdir(filepath) if f.endswith('.jpg')]
    return images

然后你需要在你的add_category函数中对这个值做一些事情:

def add_category(request):
    ...
    else:
        imageArray = imgArray()
    return render(request, 'imgpage/add_category.html', {imageArray: imageArray})

我是这样做的:views.py

#importing json
import json
from django.core.serializers.json import DjangoJSONEncoder
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 )
    json_list = json.dumps(list(imageArray), cls=DjangoJSONEncoder)
    return json_list
def add_category(request):
    # A HTTP POST?
    if request.method == 'POST':
        #Do something
    else:
        # If the request was not a POST, display the form to enter details.
        imageArray = imgArray(request)
        context = {'imageArray': imageArray}
        return render(request, 'imgpage/add_category.html',context)
    return render(request, 'imgpage/add_category.html')

和add_category.html:

<script type="text/javascript">
            var images = {{imageArray|safe}};               
            document.getElementsByTagName("img")[0].src =  DJANGO_STATIC_URL+"images/"+images[1];
        </script>

希望这能帮助到一些人:)干杯!