Search code examples
dust.js

Is there a way to differentiate between false and undefined in a dust template?


Is there any way to differentiate between false and undefined in a dust template? I believe:

{^myVariable}
    Hello
{/myVariable}

would print Hello if myVariable is undefined right?


Solution

  • As you've noticed, Dust doesn't compare on truthiness, but on "emptiness", so you can't specifically check for a variable's falsiness.

    You can use the {@eq} comparator instead, but you have to be careful with what you compare. You can't blindly use the Javascript keyword undefined, because Dust will just read it as a reference to the variable undefined (which is probably safe, but could give you a bug). So this is OK:

    {@eq key=myVariable value="undefined" type="string"}myVariable is undefined{/eq}
    {@eq key=myVariable value=somethingImSureDoesntExist}myVariable is undefined{/eq}
    

    But you can't test the reverse, since using type="boolean" will cast both key and value

    {@eq key=myVariable value="false" type="boolean"}
      myVariable might be 0, undefined, null, false, etc...
    {/eq}
    {@eq key=myVariable value=somethingInContextIKnowIsAlwaysFalse}
      This is sloppy because you have to include a dummy "false" in your context, but it works!
    {/eq}
    

    So if you really need to test === false, you should write a quick helper:

    dust.helpers.isFalse = function(chunk, context, bodies, params) {
      return context.resolve(params.key) === false;
    }
    

    And use it like:

    {@isFalse key=myVariable}
      myVariable is exactly false!
    {:else}
      myVariable is something else
    {/isFalse}
    

    All this said, you will probably be much happier if you allow Dust to use its emptiness checks instead, by not requiring your templates to care about the difference between undefined and false.