Everyone_Else Everyone_Else - 1 year ago 64
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?

Answer Source

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 %}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download