I tried to use an if
helper as follows:
{{#if existingDaysIds.includes(weekday.id)}}
<p>includes</p>
{{/if}}
and it failed:
emplate Compiler Error (TemplateCompiler) in .../templates/working-hours.hbs
Parse error on line 6:
...#if existingDaysIds.includes(1)}}
-----------------------^
Expecting 'ID', got 'INVALID'
When I display existingDaysIds
array:
<p>{{existingDaysIds}}</p>
it displays the number I’d like to check:
0,1,2,3,4,5,6
What’s wrong with that ?
Handlebars will only work with values, it won’t run any code directly but you can use helpers to augment the basic functionality.
There could be two ways to do what you want depending on your requirements:
-
Add a computed property (CP) to your working-hours
controller, something like:
export default Controller.extend({
existingDayIds: ...,
weekday: ...,
existingDaysIncludesSelectedWeekday: computed('existingDayIds.[]', 'weekday.id', function () {
let existingDayIds = this.get('existingDayIds');
let weekday = this.get('weekday');
return existingDayIds.includes(weekday.get('id'))
}
});
then in your template you can do:
{{#if existingDaysIncludesSelectedWeekday}}
<p>includes</p>
{{/if}}
-
Use an includes
type helper in your template. ember-composable-helpers includes such a {{contains}}
helper that you can use in a handlebars sub-expression.
{{#if (contains weekday.id existingDayIds)}}
<p>includes</p>
{{/if}}
Option 1 is usually preferable when you’re working with complex data or manipulations. Option 2 can be a nice way to be more declarative in your templates but beware of putting too much logic there, it can become difficult to reason about and unit test.
1 Like
@lookingsideways: Thank you very much for such a detailed explanation, really useful for someone like me who is in the very beginning of his Ember way.