Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass data from python to javascript in web2py

I see some relevant posts to my query.

Tornado is used in the below link How to pass variable from python to javascript

I know that it can be done using json but I am not clear how to implement it. In the web2py default controller I am returning a dictionary which contains the latitudes and longitudes.

def index():
    lat_long_list=[]
    info1 = {'lat':'1.0032','long':'2.00003','name':'Akash'}
    info2 = {'lat':'1.2312','long':'-1.0034','name':'Kalyan'}
    lat_long_list.append(info1)
    lat_long_list.append(info2)
    return dict(lat_long_list=lat_long_list)

In java script I want to iterate through the list of dictionaries and mark the points on the google maps.

I cannot say

<script>
 {{ for lat_long_rec in lat_long_list :}}
 var name = {{=lat_long_rec['name']}}
 {{ pass }}
</script>

This fails. An alternative to handle this is to write the list into an xml and from javascript read the file but I dont want to achieve it this way as writing to file is non performant. Let me know how best this can achieved.

like image 678
Pradeep Kumar Anumala Avatar asked Sep 28 '22 10:09

Pradeep Kumar Anumala


1 Answers

Convert the Python list to JSON and pass that to the view to insert in the Javascript code:

    from gluon.serializers import json
    return dict(lat_long_list=json(lat_long_list))

In the view:

<script>
    ...
    var latLongList = {{=XML(lat_long_list)}}
    ...
</script>
like image 164
Anthony Avatar answered Oct 25 '22 13:10

Anthony