Templating Using template features in Semantic UI Guide

Templating

What is Templating

Templates provide a syntax for generating html that can be used to power your components. They allow for looping, conditionals, expressions, and a data context to make it easier to retrieve data when rendering web components.

Template Syntax

Templates all support either single or double bracket syntax and are whitespace insensitive. Use what style you and your team prefer.

Single Bracket

Welcome, { getFirstName }

Double Bracket

Welcome, {{ getFirstName }}

Flexible Dialects - Compiling templates is inexpensive so supporting additional syntaxes comes at little cost. For people coming from a jsx or svelte background single bracket notation might feel more familiar. For those coming from meteor, rails, or php using double brackets might be more at home. Both achieve the same results, but allow for developer and team preference.

Template Usage

Templates compile to an ast that is used to create the Shadow DOM of web components. This makes sure that only the parts that need updating in your component are modified when reactive changes occur.

Components include a custom templating language built for web components. This language compiles to an Abstract Syntax Tree or AST that is used to render your component and surgically update portions of the DOM when reactive data sources change.

For more information about how templates are used inside components see the dedicated section for component templates

Template Features

Expressions

Expressions allow values to be ouput and functions to be executed from the template’s data context.

Value Output

{name}

Function Calls

{someMethod argumentOne argumentTwo}

Complex Nested Expressions

{formatDateTime someDate 'YYYY-MM-DD HH:mm' (object timezone='local')}

Nested expressions

{formatDate (getDate now) 'h:mm a'}

HTML Output

{#html someHTML}

Conditionals

If / elseif / else

{#if isColor 'red'}
Red
{else if isColor 'blue'}
Blue
{else}
Another color
{/if}

Loops

With intermediate value

{#each row in someCollection}
{row.name}
{/each}

With inner data context

{#each someCollection}
{name}
{/each}

With array index

{#each someCollection}
{@index}
{/each}

Content Slots

Default Slot

{>slot}

Named Slot

{>slot icon}

Global Helpers

Built-in helpers

{stringify someObject}
{formatDate someDate}
{log 'Hello World'}

Subtemplates

Named Templates

{> exampleSubtemplate}

Dynamic Template Support

{>template
name=getTemplateName
data={
afternoon: 'Biking',
evening: getEveningActivity,
}
}

Reactive Data Controls

{>template
name=getTemplateName
reactiveData={
morning: morningActivity,
}
data={
afternoon: 'Biking',
evening: eveningActivity,
}
}

Snippets

{#snippet fullName}
{#if both firstName lastName}
{firstName} {lastName}
{else}
{lastName}
{/if}
{/snippet}
{#if isLoggedOut}
Login, {>fullName}
{else if hasName}
Login, {>fullName}
{else}
Login
{/if}