Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass null to javascript from python using jinja

I was doing it something like this in google app engine:

self.render('hello.html', value=null)

But obviously since python doesn't understand null it thinks it's an undefined variable and gives an error.

If I send it as a string (value="null") then javascript doesn't know that I mean null and not a string "null".

So what's the way to get around this?

And if it's any bit pertinent, I'm trying to pass the value null to a google scatter chart in javascript.

like image 625
afroze Avatar asked Dec 20 '22 20:12

afroze


2 Answers

I'm assuming your are doing something like:

self.render('hello.html', value=[0.1, None, None, 0.5])

and having the template engine convert that to a string, so you end up with:

 [0.1, None, None, 0.5]

If so, you should have python convert it to javascript before passing to jinja:

import json
self.render('hello.html', value=json.dumps([0.1, None, None, 0.5]))

That'll give you:

[0.1, null, null, 0.5]

which is what I think you are after.

A even better solution would be to add a custom filter to jinja to handle javascript escaping. That would look something like:

import json
def jsonfilter(value):
    return json.dumps(value)

environment.filters['json'] = jsonfilter

Then in your template you could just do

{{value|json}}
like image 120
cnelson Avatar answered Dec 23 '22 11:12

cnelson


assuming your template looks something like:

plotdata = [0.1, {{value}}, null, 0.5]

(depending on the template engine you are using), then:

self.render('hello.html', { "value": "null" })

should result in the rendered template producing:

plotdata = [0.1, null, null, 0.5]

If this is not working, please tell us the template engine you are using, the values you've tried sending, and the exact result of rendering..

like image 33
lecstor Avatar answered Dec 23 '22 11:12

lecstor