abernier
abernier

Reputation: 28208

Dust: difference between logic sections {?} and {#}

What exactly is the difference between {?} and {#}?

--

After a little test, listing all truthy/falsy values for {?}, and comparing them to {#}:

context:

{
  values: [
    // false
    '',
    "",
    false,
    null,
    undefined,
    [],
    // true
    0,
    "0",
    "null",
    "undefined",
    "false",
    {},
    {a: 'a'}
  ]
}

template:

{#values}
 {?.}true{:else}false{/.}
{/values}
{~n}
{#values}
 {#.}true{:else}false{/.}
{/values}

it outputs EXACTLY the same result:

falsefalsefalsefalsefalsefalsetruetruetruetruetruetruetrue
falsefalsefalsefalsefalsefalsetruetruetruetruetruetruetrue

--

Is really there any difference between them ?

Upvotes: 7

Views: 3505

Answers (1)

smfoote
smfoote

Reputation: 5609

There is a difference between the # and ?, though it is somewhat subtle and doesn't reveal itself in your example.

? (exists): Checks for the truthiness of the given key. If the key is truthy, execute the body, else execute the :else body if there is one.

# (section): Checks for the truthiness of the given key. If the key is truthy, set the context to the key, then execute the body. If the context is an array, execute the body once for each element in the array. If the key is not truthy, do not change contexts, and execute the :else body if it exists.

So, if your template looked like this instead:

template:

{?values}
 {?.}true{:else}false{/.}
{/values}
{~n}
{#values}
 {#.}true{:else}false{/.}
{/values}

Then your output would be:

true
falsefalsefalsefalsefalsefalsetruetruetruetruetruetruetrue

The first line checks that values exists, but does not change the context. The second line checks that the current context (which in this case is the root context) exists, and it prints true. Since ? doesn't step into the context and loop through the array, true is only printed once.

Upvotes: 11

Related Questions