简体   繁体   English

在Django 1.8.1中将视图中的列表用作javascript模板中的数组

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

I have a piece of code in views.py that gets the file names from a directory: 我在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')

I want to use this array of image files in javascript. 我想在javascript中使用此图像文件数组。 I want to use the array of file names so that I can use js to change image source. 我想使用文件名数组,以便可以使用js更改图像源。 The print context statement yields the following output in the python console: print context语句在python控制台中产生以下输出:

{'imageArray': ['image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.
jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg']}

But I am not able to access the imageArray at all in the template. 但是我根本无法访问模板中的imageArray。 Here are the scripts I tried to test if the array has been passed, in the template html file: 这是我尝试测试模板html文件中是否已传递数组的脚本:

In add_category.html file: 在add_category.html文件中:

{% for img in imageArray %}
        <li>{{ img|safe }}</li>
        <li>{{ img }}</li>
        <p>img</p>
{% endfor %}

Also, note that the "img" inside <p> tags are also not rendered on the screen. 另外,请注意, <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>

In the above script, the first console log prints empty line in the console, while the 2nd prints "imgx=undefined" 在上面的脚本中,第一个控制台日志在控制台中打印出空行,而第二个日志则显示“ imgx = undefined”

Please suggest me ways I can use the python list as JS array. 请建议我可以将python列表用作JS数组的方法。 I use Django 1.8.1, but the service I would host on uses 1.7.x. 我使用Django 1.8.1,但是我将托管的服务使用1.7.x。 So something that would work on both would be great. 因此,对两者都适用的方法会很棒。

You have a very peculiar structure here. 您在这里有一个非常特殊的结构。 imageArray() is a view, which returns a full HttpResponse; imageArray()是一个视图,它返回完整的HttpResponse; but you call it from within another view, add_category . 但是您是从另一个视图add_category调用它的。 What's more, you do nothing at all with the result; 而且,您对结果一无所成。 it is thrown away and never passed anywhere. 它被扔掉,再也没有经过任何地方。 So, naturally, it's always going to be blank in the template. 因此,自然地,模板中总是空白。

I'm not sure exactly what you're doing, so it's hard to know what you really want here. 我不确定您在做什么,因此很难知道您在这里真正想要的是什么。 But I suspect that imageArray() should be a normal utility method, which simply returns a list of images: 但我怀疑imageArray()应该是普通的实用程序方法,该方法仅返回图像列表:

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

Then you need to actually do something with that value in your add_category function: 然后,您实际上需要在add_category函数中使用该值进行add_category

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

So here is what I did: views.py 所以这就是我所做的: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')

And in 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>

Hope this helps someone :) Cheers! 希望这可以帮助某人:)干杯!

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

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