Dust: difference between logic sections {?} and {#}
Asked Answered
K

1

7

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 ?

Kuth answered 12/8, 2013 at 10:16 Comment(0)
G
11

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.

Geneva answered 12/8, 2013 at 15:14 Comment(2)
Ok, so my example was more testing that ? and # evaluate truthiness the same way... If I sum up, # changes the context and is "array-aware" whereas ? just evaluates truthiness (the same way as # does). In other words, ? is kinda subset of #, right?Kuth
That's right. Both can be useful, depending on the situation.Geneva

© 2022 - 2024 — McMap. All rights reserved.