Search code examples
javascriptdust.js

Dust.js do not add separator after empty values in loop


I have an array of values, for instance:

 {
  "languages": [
    "",
    "CSS",
    "HTML",
    "",
    "JavaScript",
    "Dust",
    "",
    ""
  ]
}

Expected output:

CSS, HTML, JavaScript, Dust

Is it possible to not add separator after empty values in my dust template without creating custom helper? The problem is that array can have any length with any number of empty values.


Solution

  • Using only built-in helpers you can write

    {#languages}
      {@ne key=. value=""}{.}{@sep}, {/sep}{/ne}
    {/languages}
    

    However, this will leave a dangling comma if the last item in your array is a blank one. If you can find the first non-blank item in your array and pass that data, try this rather-ugly version:

    {#languages}
      {@ne key=. value=""}{@sep}{@ne key=$idx value=firstNonBlankItem}, {/ne}{/sep}{.}{/ne}
    {/languages}
    

    If firstNonBlankItem is set to the correct index (1 in your example above), you'll get what you want.

    Otherwise, you should really write a custom helper-- that's what Dust intends you to do. You don't even need to include the helper in your context; instead, you could write a custom global helper and include it with your Javascript.