30

I'm trying to send a lat/long point as a JSON object from Python to a javascript. I'm using Flask so the following is Jinja templating..

Python:

@app.route('/')
def homepage():
    lat_lng = (39.7392,-104.9847) 
    return render_template("index_v2.html", lat_lng=json.dumps(lat_lng))

html with js:

<script type='text/javascript'>
    var map;
    function initialize() {
      // Create the map.
      var lat_lng = eval('({{ lat_lng }})')
      map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 8,
        center: new google.maps.LatLng(lat_lng)
      });

    }

    google.maps.event.addDomListener(window, 'load', initialize);
  </script>

I'm using the eval because the standard Jinja notation of variable = {{ data }} isn't working and I found some advice that eval was necessary. Any advice?

1
  • What happens if you quit eval then printing lat_lng variable with, console.log(lat_lng) ??? Commented Jul 13, 2014 at 4:42

1 Answer 1

56

The Flask Jinja2 documentation covers this pretty well. The first example under the "Standard Filters" section shows exactly how to embed a JSON object from python into a Javascript script:

<script type=text/javascript>
    doSomethingWith({{ user.username|tojson|safe }});
</script>

So in this case:

var lat_lng = {{ lat_lng|tojson|safe }};

tojson calls dumps on the data, so you should pass the data directly to the template rather than calling dumps on it, otherwise you double-serialize the data and end up with a JSON string.

Sign up to request clarification or add additional context in comments.

3 Comments

Yep, read the same Flask documentation, I've tried that syntax exactly and get the console error "lat_lng is not defined". Also the line comes up with an syntax error of "invalid property id" in my IDE at exactly the column of the first curly bracket. I'm running Python 2.7 and Flask 0.10.1
And you're sure you're passing through lat_lng as a template parameter?
I just decided to go with AJAX and jquery instead of messing with it. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.