5

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.

1 Answer 1

4

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Anthony, Thanks for the response. I tried it and it's not working. I checked the source code of the html page and I see the following. <script> var v = [{&#x27;lat&#x27;: &#x27;1.0032&#x27;, &#x27;name&#x27;: &#x27;Akash&#x27;, &#x27;long&#x27;: &#x27;2.00003&#x27;}, {&#x27;lat&#x27;: &#x27;1.2312&#x27;, &#x27;name&#x27;: &#x27;Kalyan&#x27;, &#x27;long&#x27;: &#x27;-1.0034&#x27;}] </script>
Using XML has addressed the issue.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.