Question

I'm looking for a simple way to assign a value held by a javascript variable to a python variable in a webpy template. I have an int value held by a js variable that I want to use to get an element of a python array. For example (if I want $list[0] in a template):

<script>
...
foo = 0
$i = foo        ??? (doesn't work...)
return $list[ foo ]    ??? (doesn't work...)
...
</script>

Sorry if that isn't as clear as I hope it is. I've tried a ton of different ways to do this, and I can't seem to make it work. Thanks!!!

Was it helpful?

Solution

To expand on Pointy's answer, what you are asking for does not make sense because web pages code is run in a certain order, and you are trying to make it run backwards.

  1. The webserver (python) gets a request. It uses templates to construct a response for that request, and returns and HTML page and sends it to the client. At this point, generally, the python code is done running.

  2. The client (browser) gets the web page. It loads all the other resources it needs to display it, and then runs the javascript.

The javascript and python, therefore, are running on different computers at different times. The solution to your problem is probably going to be a little more complicated then you were hoping for: you have to make a server request from javascript to get the data from the server after the page is loaded on the client, and then manually add it to the DOM.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top