I have a piece of code in views.py that gets the file names from a directory:
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. I want to use the array of file names so that I can use js to change image source.
The print context statement yields the following output in the python console:
{'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. Here are the scripts I tried to test if the array has been passed, in the template html file:
In add_category.html file:
{% 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.
<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"
Please suggest me ways I can use the python list as JS array. I use Django 1.8.1, but the service I would host on uses 1.7.x. So something that would work on both would be great.