简体   繁体   中英

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.

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}}

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..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM