meteor Blaze Templating Template Helpers


Example

Template helpers are an essential part of Blaze and provide both business logic and reactivity to a Template. It is important to remember that Template helpers are actually reactive computations that are rerun whenever their dependencies change. Depending on your needs, Template helpers can be defined globally or scoped to a specific template. Examples of each Template helper definition approach is provided below.

  1. Example of a Template helper scoped to a single template.

First define your template:

<template name="welcomeMessage">
  <h1>Welcome back {{fullName}}</h1>
</template>

Then define the Template helper. This assumes that the data context of the template contains a firstName and lastName property.

Template.welcomeMessage.helpers({
  fullName: function() {
    const instance = Template.instance();
    return instance.data.firstName + ' ' + instance.data.lastName
  },
});
  1. Example of a global Template helper (this helper can be used from within any Template)

First register the helper:

Template.registerHelper('equals', function(item1, item2) {
  if (!item1 || !item2) {
    return false;
  }

  return item1 === item2;
});

With the equals helper defined, I can now use it within any template:

<template name="registration">
  {{#if equals currentUser.registrationStatus 'Pending'}}
    <p>Don't forget to complete your registration!<p>
  {{/if}}
</template>