Everyone_Else Everyone_Else - 3 months ago 9
Javascript Question

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

Suppose I have a template variable with the name

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

Answer

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 %}