Templates
On this page 36
stx provides a powerful templating system with an intuitive syntax that makes building UIs both productive and enjoyable. This page covers all template features and capabilities available in the stx ecosystem.
Template Syntax
Text Interpolation
stx uses double curly braces for safe text interpolation:
<div>{{ message }}</div>
<span>{{ user.name }}</span>
<p>{{ formatDate(post.createdAt) }}</p>
Raw HTML Interpolation
For trusted HTML content, use triple braces:
<div>{{{ trustedHtmlContent }}}</div>
Attribute Binding
Bind dynamic values to attributes:
<imgx-src=""x-alt="">
<buttonx-disabled=""x-class="">
<inputx-value=""x-placeholder="">
Conditional Rendering
Basic Conditionals
@if(userisAuthenticated)
<dashboard />
@elseif(userisGuest)
<welcome-message />
<login-form />
Short Conditionals
<admin-panel />
<login-banner />
@unless(userhasPermission)
<access-denied />
Conditional Classes
<divclass=""x-class="
'card--active': isActive,
'card--disabled': isDisabled,
'card--large': size === 'large'
}">
Content
</div>
List Rendering
Basic Loops
@foreach(itemsasitem)
<divclass="">
<h3>{{ item.title }}</h3>
<p>{{ item.description }}</p>
</div>
Loop with Index
@foreach(usersasindex=>user)
<trclass="">
<td>{{ index + 1 }}</td>
<td>{{ user.name }}</td>
</tr>
Empty State
@forelse(postsaspost)
<article>
<h2>{{ post.title }}</h2>
<p>{{ post.excerpt }}</p>
</article>
<p>No posts found</p>
Nested Loops
@foreach(categoriesascategory)
<divclass="">
<h2>{{ category.name }}</h2>
@foreach(categoryproductsasproduct)
<divclass="">
<h3>{{ product.name }}</h3>
<p>amp;#123;{ product.price }}</p>
</div>
</div>
Template Composition
Layouts
<!-- layouts/app.stx -->
<!DOCTYPE html>
<html>
<head>
<title>@yield('', '')</title>
('styles')
</head>
<body>
<header>
@include('')
</header>
<main>
@yield('')
</main>
<footer>
@include('')
</footer>
('scripts')
</body>
</html>
Template Inheritance
<!-- pages/home.stx -->
@extends('')
@section('', '')
@push('')
<linkrel=""href="">
@section('')
<h1>Welcome to our website</h1>
<p>This is the home page content</p>
@push('')
<script></script>
Partial Templates
<!-- partials/user-card.stx -->
<divclass="">
<imgx-src=""x-alt="">
<h3>{{ user.name }}</h3>
<p>{{ user.email }}</p>
</div>
<!-- Usage -->
@include(''currentUser })
Template Directives
Form Handling
<form@submit.prevent="handleSubmit">
<input@model="form"type=""required>
<input@model="form"type=""required>
<buttontype=""x-disabled="">
{{ isSubmitting ? 'Logging in...' : 'Login' }}
</button>
</form>
Event Handling
<button@click="increment">Increment</button>
<input@input="handleInput"@blur="validateField">
<div@mouseenter="showTooltip"@mouseleave="hideTooltip">
Hover me
</div>
<!-- Event modifiers -->
<form@submit.prevent="onSubmit">
<input@keyup.enter="search">
<button@click.once="initializeOnce">
Dynamic Binding
<component:is="currentComponent":props="componentProps" />
<inputattributeNameattributeValue">
<buttoneventNameeventHandler">
Template Optimization
Template Compilation
stx compiles templates to optimized JavaScript:
// Original template
const template = `
@foreach(items as item)
<div>{{ item.name }}</div>
@endforeach
`
// Compiled output (simplified)
function render(context) {
let html = ''
for (const item of context.items) {
html += `<div>${escape(item.name)}</div>`
}
return html
}
Template Caching
// Template caching configuration
const templateConfig = {
cache: {
enabled: true,
ttl: 3600, // 1 hour
invalidateOnChange: true
},
// Precompile templates
precompile: [
'layouts/**/*.stx',
'components/**/*.stx',
'pages/**/*.stx'
]
}
Lazy Loading
<!-- Lazy load heavy components -->
<suspense>
<template>
<heavy-componentlazy />
</template>
<template>
<loading-spinner />
</template>
</suspense>
Template Security
Automatic Escaping
stx automatically escapes output to prevent XSS:
<!-- Safe: automatically escaped -->
<div>{{ userInput }}</div>
<!-- Raw HTML: only for trusted content -->
<div>{{{ trustedContent }}}</div>
Content Security Policy
// CSP-compliant templates
const cspConfig = {
nonce: generateNonce(),
inlineStyles: false,
inlineScripts: false
}
// Templates automatically include nonce
<script nonce="{{ cspNonce }}">
// Safe inline script
</script>
Advanced Features
Template Slots
<!-- components/modal.stx -->
<divclass="">
<headerclass="">
<slotname="">Default Header</slot>
</header>
<mainclass="">
<slot>Default content</slot>
</main>
<footerclass="">
<slotname="">
<button@click="close">Close</button>
</slot>
</footer>
</div>
<!-- Usage -->
<modal>
<template>
<h2>Custom Header</h2>
</template>
<p>Modal content goes here</p>
<template>
<button@click="save">Save</button>
<button@click="cancel">Cancel</button>
</template>
</modal>
Scoped Slots
<!-- components/data-list.stx -->
<divclass="">
@foreach(itemsasitemindex)
<slot:item="item":index="index">
<!-- Default item template -->
<divclass="">{{ item.name }}</div>
</slot>
</div>
<!-- Usage with custom template -->
<data-list:items="users">
<template>
<divclass="">
<span>{{ index }}</span>
<strong>{{ item.name }}</strong>
<small>{{ item.email }}</small>
</div>
</template>
</data-list>
Template Macros
<!-- Define reusable template macros -->
('button', { type = 'button', size = 'medium', variant = 'primary' })
<button
type="{{ type }}"
class="btn btn--{{ variant }} btn--{{ size }}"
{{ $attributes }}
>
{{ $slot }}
</button>
<!-- Usage -->
({ variant: 'secondary', size: 'large' })
Click me
Template Testing
Template Unit Tests
import { renderTemplate } from '@stacksjs/testing'
test('user list template', () => {
const template = `
@foreach(users as user)
<div class="user">{{ user.name }}</div>
@endforeach
`
const context = {
users: [
{ name: 'John Doe' },
{ name: 'Jane Smith' }
]
}
const html = renderTemplate(template, context)
expect(html).toContain('<div class="user">John Doe</div>')
expect(html).toContain('<div class="user">Jane Smith</div>')
})
Snapshot Testing
test('component template snapshot', () => {
const component = renderComponent('UserCard', {
user: { name: 'John', email: 'john@example.com' }
})
expect(component.html()).toMatchSnapshot()
})
Related Resources
- Template Syntax Guide - Comprehensive template syntax guide
- Component System - Building reusable components
- Directives - Custom template directives
- Performance - Template performance optimization