Unable to pass jinja2 variables into javascript snippet

57,829

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

Share:
57,829

Related videos on Youtube

deeshank
Author by

deeshank

learn, code, make, think !

Updated on July 09, 2022

Comments

  • deeshank
    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
      Jakob Bowyer over 10 years
      {{ name|safe }} should work
    • deeshank
      deeshank over 10 years
      @JakobBowyer - it dint work :(
    • Code Review Doctor
      Code Review Doctor over 10 years
      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 djangoData = $('#my-data').data();
  • deeshank
    deeshank over 10 years
    Thanks @rikAtee. I followed the same logic.. just that i used normal div instead.
  • jonprasetyo
    jonprasetyo about 9 years
    It 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
    Andrejs Cainikovs about 9 years
    Niiiice! Now I can totally isolate html from javacript. This will allow me a clean integration with Flask-Assets. Thanks!
  • Bill Cheatham
    Bill Cheatham over 8 years
    I'm struggling to understand how the html syntax corresponds to the original question. Is data-name an arbitrary string, or does it have to be data-name? Or just start with data-? Where has the other variable come from?
  • jon_two
    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
    nycynik about 8 years
    I guess I understand the bad idea thing, but how do I do charts? I have 50-60 data points to plot.
  • Alexey
    Alexey over 7 years
    I 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
    Zichen Wang over 7 years
    I think this doesn't work if name contains line breaks such as '\n'. It will throws a javascript syntax error.
  • Luke Murray
    Luke Murray over 7 years
    Here 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
    e-info128 about 3 years
    Escape 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
    Nisanth Reddy about 3 years
    Hi There. Try elaborating or post a comment.
  • emilaz
    emilaz almost 3 years
    When using with more complex syntax like JSON.parse('{{ url_for(\'foo.bar\', filename = \'foobar.txt\') | tojson }}');, this gives an Uncaught SyntaxError: Unexpected token { in JSON at position 1
  • Pedro Rodrigues
    Pedro Rodrigues almost 3 years
    That 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
    emilaz almost 3 years
    It's still not clear what data-other is here and what it should be set to.