Search code examples
nunjucksgulp-nunjucks-render

Check for NaN in nunjucks template?


I'm trying to display 'n/a' instead of NaN in a popup. Something like:

    {% if value == NaN %} 
        n/a
    {% endif %}

I realize I can always catch it earlier on before the template is rendered but
Is there was a way to check for NaN values in the template?


Solution

  • Here is the logic for a custom filter since there is not a built in filter to check for NaN:

    nunjucks.configure().addFilter('nan', function(num) {
         if (isNaN(num)){
            return 'n/a';
         }
         return num;
    });
    

    Then the usage is the same as for any filter:

    {{ num | nan }}