Template Helpers Using helpers for common template operations Guide
Categories

Template Helpers

Usage

Template helpers are special utilities that are available across all templates and provide utilities like classMap, formatDate, concat stringify that can be used to format values for output.

Literate Coding

Helpers can often mimic the functionality of simple javascript expressions but can be used to improve the readability of your templates, or reduce their reliance on inlined javascript.

Using Helper
{#if hasAny arrayItems}
...
{/if}
Identical Javascript
{#if arrayItems.length > 0}
...
{/if}

Shared Utilities

Helpers also provide common utilities from utils which make it easier to manipulate data without writing additional methods in your component

With Helper

Using Stringify
{stringify complexData}

Without Helper

Using Data Context
{outputString complexData}
Custom Stringify
const createComponent = ({ }) => ({
outputString(value) {
return JSON.stringify(value);
}
});

Helper Example

In this example formatDate is used to format the display of a date set in the components state.

{formatDate currentTime 'h:mm:ss a'}

Built-in Helpers

Semantic UI provides dozens of built-in template helpers for common operations like formatting, logic, CSS classes, and more. For a complete reference of all available helpers, see the Template Helpers API Documentation.

Custom Helpers

You can extend the template system by registering your own helper functions using registerHelper and registerHelpers.

Single Helper Registration

import { registerHelper } from '@semantic-ui/templating';
registerHelper('formatMoney', (amount, currency = 'USD') => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency
}).format(amount);
});

Multiple Helper Registration

import { registerHelpers } from '@semantic-ui/templating';
registerHelpers({
initials: (name) => name.split(' ').map(n => n[0]).join('').toUpperCase(),
randomId: () => Math.random().toString(36).substr(2, 9),
timeAgo: (date) => {
const seconds = Math.floor((new Date() - new Date(date)) / 1000);
if (seconds < 60) return 'just now';
if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`;
if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`;
return `${Math.floor(seconds / 86400)}d ago`;
}
});

Using Custom Helpers

Once registered, custom helpers work like built-in helpers:

<p>Price: {formatMoney 29.99}</p>
<p>User: {initials 'John Smith'}</p>
<p>ID: {randomId}</p>
<p>Created: {timeAgo createdDate}</p>
Previous
Snippets
Next
Reactivity