sending data as JSON object from Python to Javascript with Jinja

39,924

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.

Share:
39,924
tesslins
Author by

tesslins

Updated on July 09, 2022

Comments

  • tesslins
    tesslins almost 2 years

    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?