Add items from a python list to a javascript array

Denis McMahon denismfmcmahon at gmail.com
Sat Sep 19 09:58:04 CEST 2015


On Sat, 19 Sep 2015 00:25:20 -0700, Darryl Doherty wrote:

> I have a kiosk for digital signage which has a html index file with a
> javascript which rotates through other html files using iframe at timed
> intervals. What I want to do is edit the array in the index file with
> Python to add and remove the HTML file paths from the array. I have a
> list of all file paths in the python list, so I want to select a path
> from the list and add it to the javascript array. In addition I want to
> be able to use python to remove file paths from the array when needed.
> I'm new to Python so some code examples would be appreciated. Thanks.

I'm going to assume that the whole web page is being generated by python 
code with the web server, and that the list of files is available in the 
python code at the time of web page generation.

First of all, you need to create a python list of the file names to use. 
This will use whatever the current data is when the web page is generated.

Secondly, you need to write this list to a suitable javascript variable 
when you construct the web page. Assuming that all the file paths are 
standard ascii with no spaces etc in them, say you have a python list 
like this:

Here is a very simple code example for a method (and there are others) of 
embedding such a list of paths held in python within a javascript 
variable inside a script element in a web page:

#!/usr/bin/python

files = ["/a/a.htm", "/a/b.htm", "/a/c.htm"]

page = "<html><head><script>\n"

fmt = "var frames=Array({});\n"

page += fmt.format(",".join(map(lambda x:'"'+x+'"', files)))

page += "</script></head><body></body></html>\n"

print page


-- 
Denis McMahon, denismfmcmahon at gmail.com


More information about the Python-list mailing list