58

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?

simeg
  • 1,889
  • 2
  • 26
  • 34
deeshank
  • 4,286
  • 4
  • 26
  • 32

7 Answers7

80

Try with quotes:

alert("{{name}}");
ndpu
  • 22,225
  • 6
  • 54
  • 69
  • 10
    I think this doesn't work if `name` contains line breaks such as '\n'. It will throws a javascript syntax error. – Zichen Wang Dec 21 '16 at 15:38
76

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
Rich Tier
  • 9,021
  • 10
  • 48
  • 71
  • Thanks @rikAtee. I followed the same logic.. just that i used normal div instead. – deeshank Feb 08 '14 at 17:24
  • 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 – jonprasetyo Mar 21 '15 at 16:06
  • Niiiice! Now I can totally isolate *html* from *javacript*. This will allow me a clean integration with Flask-Assets. Thanks! – Andrejs Cainikovs May 11 '15 at 13:05
  • 4
    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? – Bill Cheatham Feb 16 '16 at 11:33
  • @BillCheatham it looks like djangoData is an object with the properties name and other. So you can access the name by using djangoData.name. – jon_two Mar 16 '16 at 14:32
  • I guess I understand the bad idea thing, but how do I do charts? I have 50-60 data points to plot. – nycynik Apr 12 '16 at 02:24
  • 2
    I think it's worth to mention that you can't give any name to variables inside meta tag, so first I've tried and offcause it don't work. So make variables like this . It's must be clear from answer, but for some reason it wasn't clear for me at first. – Alexey Sep 03 '16 at 08:04
  • Here is the option offered from flask. They recommend using the json filter http://flask.pocoo.org/docs/0.12/templating/#standard-filters `` – Luke Murray Feb 08 '17 at 14:37
  • It's still not clear what `data-other` is here and what it should be set to. – emilaz Jul 27 '21 at 10:45
  • .data() returns object. .data("name") returns the value. – elyte5star Sep 11 '22 at 20:08
16

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/

mr_info
  • 171
  • 1
  • 7
  • 2
    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 }}');`. – e-info128 Mar 08 '21 at 04:01
6

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 }}');
Pedro Rodrigues
  • 2,520
  • 2
  • 27
  • 26
  • 1
    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` – emilaz Jul 08 '21 at 11:36
  • 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. – Pedro Rodrigues Jul 09 '21 at 12:36
4

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

Suraj
  • 607
  • 10
  • 16
1

you can try alert({{name|safe}});

1

<input type="hidden" name="token_idx" id="token_idx" value='{{token|safe }}'

let token_data = document.getElementById("token_idx").value;

elyte5star
  • 167
  • 5