deeshank deeshank - 1 year ago 65
Javascript Question

Unable to pass jinja2 variables into javascript snippet

How do i pass jinja2 data into javascript.
I have a Flask REST url as


I am trying use
to query the above URL and hence would want to pass the jinja2 data which has the testcasename to

sample code:

<script type="text/javascript">

It doesn't work.
Any suggestions please?

Answer Source

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