Everyone_Else Everyone_Else - 6 months ago 16
Javascript Question

How to load a possibly undefined template variable with a default value?

Suppose I have a template variable with the name

. I know that I can access it in the javascript with
var myvarname = {{ myvar }};
. However, sometimes
isn't defined and the above line crashes in that case. How can I instead load it in with a default value?


Per the jinja template docs you can use the default() function like:

var myvarname ={{ myvar |default('0') }}

Or, per the flask documentation, you could use an if statement like:

{% if name %}
  var myvarname = {{ myvar }};
{% else %}
  var myvarname = 0;
{% endif %}