Conditionals
Control what's rendered based on reactive data using {{#if}} and {{#unless}}.
Basic {{#if}}
The block renders when the value is truthy. Blaze considers these falsy:
falsenullundefined0""(empty string)[](empty array — Blaze-specific!)
{{else}} Branch
{{#unless}}
The inverse of {{#if}} — renders when the value is falsy:
{{#unless}} also supports {{else}}:
Using Helpers
Conditionals can use helpers that return boolean values:
ts
Template.taskList.helpers({
hasActiveTasks() {
return Tasks.find({ completed: false }).count() > 0;
},
isOverdue() {
return this.dueDate && this.dueDate < new Date();
},
canEdit() {
return this.ownerId === Meteor.userId() || Roles.userIsInRole(Meteor.userId(), 'admin');
},
});Nested Conditionals
Inline Conditional Patterns
Conditional CSS Classes
Conditional Attributes
Nested Expressions in Conditionals
Use parentheses for complex conditions:
Register the comparison helpers:
ts
Template.registerHelper('and', (a, b) => a && b);
Template.registerHelper('or', (a, b) => a || b);
Template.registerHelper('not', (a) => !a);
Template.registerHelper('eq', (a, b) => a === b);
Template.registerHelper('gt', (a, b) => a > b);
Template.registerHelper('lt', (a, b) => a < b);
Template.registerHelper('gte', (a, b) => a >= b);
Template.registerHelper('lte', (a, b) => a <= b);Complete Example: Notification Center
ts
Template.notificationCenter.onCreated(function () {
this.isOpen = new ReactiveVar(false);
this.autorun(() => {
if (this.isOpen.get()) {
this.subscribe('notifications');
}
});
});
Template.notificationCenter.helpers({
isOpen() {
return Template.instance().isOpen.get();
},
isLoading() {
return !Template.instance().subscriptionsReady();
},
unreadCount() {
return Notifications.find({ read: false }).count();
},
hasNotifications() {
return Notifications.find().count() > 0;
},
notifications() {
return Notifications.find({}, { sort: { createdAt: -1 } });
},
});
Template.notificationCenter.events({
'click .bell'(event, instance) {
instance.isOpen.set(!instance.isOpen.get());
},
'click .mark-all-read'() {
Meteor.call('notifications.markAllRead');
},
});