I'm wondering how to access previous element in {{#each items}} loop. For example Template.index.messages returns array of objects with name and message:
{{#each messages}}
{{#if previousMessage.name != this.name }}
{{name}}
{{/if}}
{{this.message}}
{{/each}}
Basically I would like to hide name in consecutive messages. I made a workaround by filtering the messages in Template.index.messages, but that method is called every time data changes and therefore costs a lot of resources. So, how to do it in spacebars?
Thanks in advance.
The Spacebars template language is not really built for complex logic, so I wouldn't try to do this straight in the template itself. Regardless of where you implement the name-hiding code, it is going to use resources -- so doing it in the helper function like you already are is probably the easiest/best way to do it. As a side note, spacebars
doesn't handle equality statements like !=
, you have to make a helper function for that.
If you are really concerned about the computation time, the only way to reduce it would be to store more data in the database (such as the name of the last message). If you store this (for example, in .previousName
), it would be as simple as:
In the template:
{{#each messages}}
{{#if notEqual previousName name}}
{{name}}
{{/if}}
{{message}}
{{/each}}
In the javascript:
Template.index.helpers({
notEqual: function (string1, string2) {
return string1 !== string2;
}
});