SharePoint  

Using Built-in Handlebars Helpers in SPFx: A Practical Guide

Handlebars also comes with built-in helpers, little tools that make it easier to work with data.

Let’s look at the most common built-in helpers, how they work, and how you can use them in SPFx.

1. {{#if}} — Show something only if it's true

This helper checks if a value is true or exists.

You can use the if helper to conditionally render a block. If its argument returns false, undefined, null, "", 0, or [], Handlebars will not render the block.

Template

const template = `
  {{#if isAdmin}}
    <p>Welcome, Admin!</p>
  {{else}}
    <p>You are not an admin.</p>
  {{/if}}
`;

Data

const data = { isAdmin: true };

Result

<p>Welcome, Admin!</p>

2. {{#each}} — Loop through a list

This helper loops through an array and shows each item.

Template

const template = `
  <ul>
    {{#each items}}
      <li>{{this}}</li>
    {{/each}}
  </ul>
`;

Data

const data = {
  items: ['Apples', 'Bananas', 'Cherries']
};

Result

<ul>
  <li>Apples</li>
  <li>Bananas</li>
  <li>Cherries</li>
</ul>

3. {{#with}} — Focus on a nested object

If your data has objects inside objects, it helps you focus on just one part.

Template

const template = `
  {{#with user}}
    <p>{{name}} - {{email}}</p>
  {{/with}}
`;

Data

const data = {
  user: {
    name: 'John Doe',
    email: '[email protected]'
  }
};

Result

<p>John Doe - [email protected]</p>

4. {{this}} — Show current item

When you're in a loop (each), {{this}} means "the current item."

Example

{{#each fruits}}
  <li>{{this}}</li>
{{/each}}

If fruits = ["Apple", "Orange"], it shows.

<li>Apple</li>
<li>Orange</li>

5. How to Compare Values?

Handlebars doesn't let you compare like {{#if x == y}} by default.

To do this, create a small helper called ifEquals.

Helper

Handlebars.registerHelper("ifEquals", function (a, b, options) {
  return a === b ? options.fn(this) : options.inverse(this);
});

Template

{{#ifEquals role "admin"}}
  <p>You are an admin.</p>
{{else}}
  <p>You are a user.</p>
{{/ifEquals}}

Example in SPFx

Template

const template = `
  <h3>User List</h3>
  <ul>
    {{#each users}}
      <li>
        {{#if isActive}}
          <strong>{{name}}</strong> (Active)
        {{else}}
          <span style="color: gray;">{{name}}</span> (Inactive)
        {{/if}}
      </li>
    {{/each}}
  </ul>
`;

Data

const data = {
  users: [
    { name: "Alice", isActive: true },
    { name: "Bob", isActive: false }
  ]
};

const html = Handlebars.compile(template)(data);
this.domElement.innerHTML = html;

Output HTML

<h3>User List</h3>
<ul>
  <li><strong>Alice</strong> (Active)</li>
  <li><span style="color: gray;">Bob</span> (Inactive)</li>
</ul>

Conclusion

These helpers save time and make your code cleaner and easier to understand. If you need more complex logic, you can even make your own helpers.

Handlebars is great when you want your design (HTML) and logic to stay separate.