I'm learning and I'm stuck with something I can't understand.
I have a simple hello world app built with python GAE and webbapp2.
I want to display a chart on the front-end using D3.js
If I'm able to display some data directly into the HTML section of my front-end (<p>{{data}}</p>
) I'm not able to pass any data within the <script> </script>
tag of my front-end.
Here is the MainHandler
of my back-end :
MainHandler(webapp2.RequestHandler):
def get(self):
data = [{'Letter': 'A', 'Freq': 20 },{'Letter' : 'B','Freq': 12},{'Letter' : 'C','Freq': 47}]
template_values = {
'data' : data
}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))
app = webapp2.WSGIApplication([
('/', MainHandler),
], debug=True)
In the Front-end I have a simple console.log({{data}})
which is causing the following error Unexpected token &
I guess there is something I don't understand here but I don't know what.
The templating engine is escaping your data, to prevent it from confusing the browser's rendering engine, or causing security issues. So
[{'Letter': 'A', 'Freq': 20 }]
is rendered as
[{'Letter': 'A', 'Freq': 20}]
or
[{&#quot;Letter&#quot;: &#quot;A&#quot;, &#quot;Freq&#quot;: 20}]
This is confusing console.log
, which is a javascript function that doesn't know about html escaping.
You can override this behaviour in Jinja2 using the safe filter.
console.log({{ data|safe }})
Note that you should only override escaping on trusted data.