olado / doT

The fastest + concise javascript template engine for nodejs and browsers. Partials, custom delimiters and more.
Other
5.01k stars 1.02k forks source link

How to render array items split with a separator #278

Closed IlyaKhD closed 6 years ago

IlyaKhD commented 6 years ago

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"
}
zlumer commented 6 years ago

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

zlumer commented 6 years ago

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}},{{?}}
{{~}}
IlyaKhD commented 6 years ago

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

2) you can access the out variable of a template function:

{{ out = out.slice(0, -1); }}

This also removes the latest char.

pke commented 11 months ago
{{~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.