$idx and $len in a dust.js conditional statement
Asked Answered
H

2

12

The documentation on dust is just awful, I've already perused everything I can possibly find and cannot figure out how this is supposed to work.

I'm having this problem with the supposed special values $idx and $len, which, if I have guessed correctly, return the current index while iterating over an array-like section and the length of said array-like section. I have an @if condition (multiple actually) that I'm trying to workout to format a template, and the values are just not working as near as I can tell, which brings me to the following questions:

  1. Are $idx and $len actual specials in dust.js?
  2. Can you use them in an @if, and if so, how?
  3. Assuming 1=true, is $idx zero-based?

Here is my template:

{#myArray}
  {name}{@sep}, {/sep}{@if cond="('{$idx}' == '{$len} - 2')"}and {/if}{@if cond="('{$idx}' == '{$len} - 1')"}{@if cond="('{$len}' == '1')"} is {:else} are {/if}here.{/if}
{/myArray}

What it's supposed to do:

  • If there is one person, render the string "Jake is here."
  • If there are two people, render the string "Jake and John are here."
  • If there are three or more people, render the string "Jake, John, and Bill are here." (obviously, adding the comma-separated names as necessary)

If the $idx and $len specials work the way one would think they work, this template would do what I want it to, as near as I can tell, however, I don't think either of $idx or $len (or both) are implemented. If they are not, how do I create a template that does what I want?

Haim answered 10/8, 2012 at 22:29 Comment(0)
T
5
  1. Yes, they are special helpers in Dust.
  2. But according to the dustjs-linkedin wiki (under the @if section), they cannot be used inside lists of primitives. In such cases you must use the following syntax:

    {@idx}{.}{/idx}
    

Same applies with length. So, you're template would something like the template in this jsFiddle.

3.Yes, $idx and @idx are zero based. (See here for more info).

Toole answered 12/8, 2012 at 20:49 Comment(2)
There's a small error in the fiddle... the check for is/are needs to check if === 0, not 1. Otherwise, perfect, thanks!Haim
@RobertC.Barth Thanks. I've updated the jsFiddle link with the updated logic.Toole
T
0

But according to the dustjs-linkedin wiki (under the @if section), they cannot be used inside lists of primitives. In such cases you must use the following syntax:

{@idx}{.}{/idx}

this has changed now, and even in primitives the $idx and $len works

Transmontane answered 12/9, 2012 at 2:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.