Unable to pass jinja2 variables into javascript snippet
Solution 1
other than encapsulating the variable in a string, an alternate is jquery for profit:
its generally a bad idea to mix template language with javascript. An alternative would be to use html as a proxy - store the name in an element like so
<meta id="my-data" data-name="{{name}}" data-other="{{other}}">
then in the javascript do
var djangoData = $('#my-data').data();
this has advantage in:
- javascript no longer tied to the .html page
- jquery coerces data implicitly
Solution 2
Try with quotes:
alert("{{name}}");
Solution 3
I know this is a kinda old topic, but since it attracts a lot of views I suppose some people are still looking for an answer.
Here's the simplest way to do it:
var name = {{name|tojson}};
It will 'parse' whatever 'name' is and display it correctly: https://sopython.com/canon/93/render-string-in-jinja-to-javascript-variable/
Solution 4
I just figure I would add the solution I ended up using.
It has a few advantages over the other answers:
- It is 100% valid javascript at the template level (no editor/lint errors).
- Does not need any special HTML tag.
- No dependencies (jquery, or otherwise).
let data = JSON.parse('{{ data | tojson }}');
Solution 5
This is how I did it
My html Element
<!--Proxy Tag for playlist data-->
<meta id="my_playlist_data" data-playlist="{{ playlist }}">
My script element
// use Jquery to get data from proxy Html element
var playlist_data = $('#my_playlist_data').data("playlist");
See .data() documenttation for more
Related videos on Youtube
Comments
-
deeshank almost 2 years
How do i pass jinja2 data into javascript. I have a Flask REST url as
/logs/<test_case_name>
I am trying use.getJSON()
to query the above URL and hence would want to pass the jinja2 data which has the testcasename to.getJSON
function.sample code:
<script type="text/javascript"> alert({{name}}); </script>
It doesn't work. Any suggestions please?
-
Jakob Bowyer over 10 years
{{ name|safe }}
should work -
deeshank over 10 years@JakobBowyer - it dint work :(
-
Code Review Doctor over 10 yearsits generally a bad idea to mix template language with javascript. An alternative would be to use html as a proxy - store the name in an element like so <meta id="my-data" data-name="{{name}}" data-other="{{other}}">, then in the javascript do djangoData = $('#my-data').data();
-
-
deeshank over 10 yearsThanks @rikAtee. I followed the same logic.. just that i used normal div instead.
-
jonprasetyo about 9 yearsIt works but, I think that is a very overkill method - your html file will be bloated with data attributes, I think the answer below (ndpk's) is a better approach
-
Andrejs Cainikovs about 9 yearsNiiiice! Now I can totally isolate html from javacript. This will allow me a clean integration with Flask-Assets. Thanks!
-
Bill Cheatham over 8 yearsI'm struggling to understand how the html syntax corresponds to the original question. Is
data-name
an arbitrary string, or does it have to bedata-name
? Or just start withdata-
? Where has theother
variable come from? -
jon_two about 8 years@BillCheatham it looks like djangoData is an object with the properties name and other. So you can access the name by using djangoData.name.
-
nycynik about 8 yearsI guess I understand the bad idea thing, but how do I do charts? I have 50-60 data points to plot.
-
Alexey over 7 yearsI think it's worth to mention that you can't give any name to variables inside meta tag, so first I've tried <meta id="geodata" test="{{test}}"> and offcause it don't work. So make variables like this <meta id="geodata" data-test="{{test}}">. It's must be clear from answer, but for some reason it wasn't clear for me at first.
-
Zichen Wang over 7 yearsI think this doesn't work if
name
contains line breaks such as '\n'. It will throws a javascript syntax error. -
Luke Murray over 7 yearsHere is the option offered from flask. They recommend using the json filter flask.pocoo.org/docs/0.12/templating/#standard-filters
<script type=text/javascript> doSomethingWith({{ user.username|tojson|safe }}); </script>
-
e-info128 about 3 yearsEscape secuence for json is equals to javascript but when add a change in json its broken javascript. For better results respect standars:
var name = JSON.parse('{{ name | tojson }}');
. -
Nisanth Reddy about 3 yearsHi There. Try elaborating or post a comment.
-
emilaz almost 3 yearsWhen using with more complex syntax like
JSON.parse('{{ url_for(\'foo.bar\', filename = \'foobar.txt\') | tojson }}');
, this gives anUncaught SyntaxError: Unexpected token { in JSON at position 1
-
Pedro Rodrigues almost 3 yearsThat might very well be a bug then. My understanding is the filter is a wrapper around
json.dumps
, not really sure but I doubt anyone implemented a json encoder for this. -
emilaz almost 3 yearsIt's still not clear what
data-other
is here and what it should be set to.