【问题标题】:Using list from views in Django 1.8.1 as an array in javascript template在 Django 1.8.1 中使用视图列表作为 javascript 模板中的数组
【发布时间】: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 %}

另外,请注意&lt;p&gt; 标签内的“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


    【解决方案1】:

    这里有一个非常奇特的结构。 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:else: imageArray = imgArray(request) context = {'imageArray': imageArray} return render(request, 'imgpage/add_category.html',context) 其中imageArray 具有imgArray 函数返回的列表。现在控制台打印:['image0.jpg', 'image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg', 'image6.jpg', 'image7.jpg', 'image8.jpg', 'image9.jpg'] imgx=我如何让 imgx 成为文件名?
    • 您已在 JS 代码中将 Django 变量括在引号中。所以 JS 会把它看作一个字符串。你真的应该使用 JSON 在 Django 和 JS 之间传递值。
    • 非常感谢!使用 JSON 效果很好。
    【解决方案2】:

    这就是我所做的: 视图.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>
    

    希望这可以帮助某人:) 干杯!

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 2018-01-29
      • 2012-07-22
      • 1970-01-01
      • 2011-09-09
      • 1970-01-01
      • 2011-01-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多