Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

dust.js

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 ?

like image 796
abernier Avatar asked Aug 12 '13 10:08

abernier


1 Answers

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.

like image 134
smfoote Avatar answered Oct 05 '22 14:10

smfoote