javascript - 使用 Django 1.8.1 中的 View 列表作为 javascript 模板中的数组

标签 javascript python arrays django templates

我在 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() 是一个 View ,它返回一个完整的 HttpResponse;但是您从另一个 View 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})

关于javascript - 使用 Django 1.8.1 中的 View 列表作为 javascript 模板中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32584686/

相关文章:

javascript - 用javascript增加 float

javascript - 在搜索框中输入文本,然后选择使用 Selenium 和 Python 自动完成

javascript - 如何从数组中去掉美元符号并只保留数字? js

python - Pandas 将 CSV 列中的 '\0' 读取为 NULL 字符并在 JSON 中打印为 Unicode

python - 使用范围作为字典中的键

java - 表达式的类型必须是数组类型,但它解析为 ArrayList(试图比较两个数组中的字符串

python - 对整个复数数组进行插值

javascript - 使用 GAS 通过 API 访问高层数据

python - 无法在 Linux 和 Windows 下构建示例模型并出现不同的错误

PHP 替换数组中的数组值