What is Handlebars?
Handlebars is a tool that lets you write HTML templates, with placeholders like {{name}}. It replaces those with real data when the page loads.
Helpers are little functions you can add to do things like.
- Make text uppercase
- Compare values
- Format phone numbers
Step 1. Add Handlebars to Your SPFx Project.
First, open a terminal and install Handlebars.
npm install handlebars --save
Then, in your code
import * as Handlebars from 'handlebars';
Step 2. Create Helpers.
Create a file like HandlebarsHelpers.ts and add.
import * as Handlebars from 'handlebars';
export function registerHelpers() {
Handlebars.registerHelper('uppercase', (text: string) => {
return text.toUpperCase();
});
Handlebars.registerHelper('ifEquals', function (a: any, b: any, options: any) {
return a === b ? options.fn(this) : options.inverse(this);
});
Handlebars.registerHelper('formatPhone', (phone: string) => {
return phone.replace(/(\d{3})(\d{3})(\d{4})/, '($1) $2-$3');
});
}
Call this in your web part onInit().
import { registerHelpers } from './HandlebarsHelpers';
export default class MyWebPart extends BaseClientSideWebPart<IMyProps> {
public onInit(): Promise<void> {
registerHelpers();
return super.onInit();
}
}
Step 3. Write Your Template.
You can create a template using a string.
const template = `
<ul>
{{#each users}}
<li>
<strong>{{uppercase name}}</strong><br/>
Role: {{role}}<br/>
Phone: {{formatPhone phone}}<br/>
{{#ifEquals status "active"}}
<span style="color: green">Active</span>
{{else}}
<span style="color: red">Inactive</span>
{{/ifEquals}}
</li>
{{/each}}
</ul>
`;
Step 4. Pass Data and Render.
Now, we pass your user data into the template.
const users = [
{ name: 'Alice', role: 'Manager', phone: '1234567890', status: 'active' },
{ name: 'Bob', role: 'Analyst', phone: '9876543210', status: 'inactive' }
];
const compiledTemplate = Handlebars.compile(template);
const html = compiledTemplate({ users });
this.domElement.innerHTML = html;
The output HTML
<ul>
<li>
<strong>ALICE</strong><br/>
Role: Manager<br/>
Phone: (123) 456-7890<br/>
<span style="color: green">Active</span>
</li>
<li>
<strong>BOB</strong><br/>
Role: Analyst<br/>
Phone: (987) 654-3210<br/>
<span style="color: red">Inactive</span>
</li>
</ul>
Conclusion
Templatization with Handlebars helpers in SPFx provides a flexible and maintainable way to build dynamic UIs. Whether you're building dashboards, directories, or data listings, separating logic from layout helps scale your SharePoint solutions more efficiently.