olado/doT

How to render array items split with a separator

IlyaKhD opened this issue · 4 comments

Hi,
Assume I have a list of items ["apple", "banana", "orange"]
How do I render this list so that its items are split with a comma?
The result should contain no trailing comma, e.g.

const fruits = {
   "apple",
   "banana",
   "orange"
}

That's kinda basic JS: array.join(',')

Though if you need more complex logic, just check whether you're iterating on a last index.

{{~it.array :value:index}}
"{{=value}}" {{? index < it.array.length - 1}},{{?}}
{{~}}

The array.join() works best for simple constructions, so a kind of last-iteration flag required.
The :value:index is the one I've expected to exists, thanks.

Btw, there are some more options (sharing experience):

  1. applying the following regexp on a rendered template makes is possible using the backspace symbol \b (deletes the latest char)
.replace(/[\s\S]{1}\x08{1}|[\s\S]{2}\x08{2}|[\s\S]{3}\x08{3}/g, "")

E.g. rendered a,b,c,\b turns to a,b,c

  1. you can access the out variable of a template function:
{{ out = out.slice(0, -1); }}

This also removes the latest char.

pke commented
{{~it.array :value:index}}
"{{=value}}" {{? index < it.array.length - 1}},{{?}}
{{~}}

This should be part of the documentation. Is there even a documentation? Not everybody can read the regex to deciper the syntax for the loop.