Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

How do i pass jinja2 data into javascript. I have a Flask REST url as /logs/ 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 -

alert({{name}});

It dint work. Any suggestions please?

share|improve this question
1  
{{ name|safe }} should work –  Jakob Bowyer Feb 7 '14 at 11:12
    
@JakobBowyer - it dint work :( –  deeshank Feb 7 '14 at 11:57
    
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(); –  rikAtee Feb 7 '14 at 13:01

2 Answers 2

up vote 6 down vote accepted

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
share|improve this answer
    
Thanks @rikAtee. I followed the same logic.. just that i used normal div instead. –  deeshank Feb 8 '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 at 16:06

Try with quotes:

alert("{{name}}");
share|improve this answer
1  
did the magic! :) –  deeshank Feb 8 '14 at 17:23

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.