Validating an empty variable in a Swig template

In Twig, I have a statement and check for an empty variable (string or array):

{% if info is empty %} ... {% endif %} 

How can I do something like this in a Swig template?

+6
source share
4 answers

Just do

 {% if !info.length %} ... {% endif %} 

This will match strings ( "" ), arrays ( [] ), and any other object that does not have a .length property with the right value.

+15
source
 {% if Object.keys(info).length != 0 %} 

for a test test of the / dict object

0
source

Please note that if you want to distinguish the undefined value from the zero value in the number type field, you need to do:

 //this test will be true only on undefined values {% if !field and field!==0 %} // note the double = !!. indeed in swig and in js !undefined and !0 are both true values // this one will be true for undefined and 0 value fields {% if !field %} 
0
source
 {% if Object.length > 0 %} {% endif %} 
0
source

Source: https://habr.com/ru/post/955927/


All Articles