Proposal for additional $ properties
See original GitHub issueI don’t want to submit a PR without some feedback about this first. Essentially, I’d like to add a handful of very useful $ properties.
Currently, we have $idx
and $len
. I’d like to add the following:
$first
- equalstrue
during the first iteration,false
otherwise$last
- equalstrue
during the last iteration,false
otherwise$count
- equals the current count of the iteration (1-based index)
I’ve come across a number of circumstances where the corresponding helpers are too verbose or don’t work. Perhaps the biggest use case is being able to use the proposed properties with comparison helpers. Some examples:
{?$first}...{/$first} <-- first item only
{^$first}...{/$first} <-- everything except the first item
{?$last}...{/$last} <-- last item only
{^$last}...{/$last} <-- everything except the last item
{@eq key=$count value=4}{/eq} <-- a specific item
I realize Dust aims to use “less logic”, but sometimes we don’t have complete control over datasets (or we have to go out of our way to adapt them). These special properties add a huge convenience to Dust templates.
Here is a simple modification to this section of the code that adds the propsed properties:
if (len > 0) {
head = context.stack && context.stack.head || {};
head.$len = len;
for (i = 0; i < len; i++) {
head.$first = i === 0;
head.$last = i === len - 1;
head.$count = i + 1;
head.$idx = i;
chunk = body(chunk, context.push(elem[i], i, len));
}
head.$idx = undefined;
head.$len = undefined;
head.$first = undefined;
head.$last = undefined;
head.$count = undefined;
return chunk;
} else if (skip) {
return skip(this, context);
}
I haven’t done extensive testing, but it’s a pretty straight-forward addition that seems to work well. (Of course, it works properly in nested loops as well.)
FWIW, I’d also suggest the aliases $index
and $length
for consistency and legibility, but that’s another discussion.
Interested to hear the developer’s and the community’s thoughts on this.
Re:
Issue Analytics
- State:
- Created 7 years ago
- Comments:8 (4 by maintainers)
Top GitHub Comments
I would suggest not placing them on head itself. See #654.
I wish there were a slightly better way to bundle these metadata together but $ props seems fine. I’m a fan. @jimmyhchan?
@jimmyhchan Making properties extensible will be incredible, especially if defaults can be overwritten with custom props (like helpers and filters). Great idea. 👍