Skip to content

The template language

Overview

Where templates live, and what one is made of.

A Weft template says what a component, a page or a layout shows for the current state. It can also hold that state, describe how it changes, load the data it needs and run timers. The framework keeps the page in step: when a value a template reads changes, the parts that depend on it render again.

This chapter introduces the shape of a template. The chapters after it define each part exactly.

Where templates live

A template is written in one of three places, and each is checked when the project compiles:

PlaceUsed for
A .weft file in app/ or components/Pages, layouts and components. The usual place.
include_template!("src/card.weft")Loading a .weft file into Rust at compile time.
template! { … }A template written inline in Rust, as tokens.

A mistake in any of them is reported with its line and column, and inside template! it's a compiler error at the offending token.

What a template is made of

A template is a list of declarations followed by a list of nodes:

// Declarations: the template's own state, derived values and handlers.
state count = 0
let doubled = count * 2
on add = count <- count + 1

// Nodes: what it shows.
section(class: "p-6") {
    h2 "Clicked {count} times"
    p "Twice that is {doubled}."
    button(@click: add) "Add one"
}
  • Declarations come first, at the top level. They are state, let and on, and load, every and after.
  • Nodes are elements, text, if and for. An element has a name, optional attributes in brackets, and optional children in braces or text on the same line.
  • Expressions compute values anywhere a value goes: in attributes, in {…} inside strings, in conditions and loops, and on the right of declarations. See Expressions and the standard functions.
  • Names a template reads but doesn't declare come from its scope: a component's props, a page's companion (page.rs), or loop variables.

A template is pure

Expressions never change anything: they read names and return values. The only things that change state are the steps of handlers and timers, and those say what the state becomes, in terms of what it was. Effects, such as requests and navigation, are described as commands and carried out by the runtime. A template therefore reads as a description of the page for any state, not a sequence of updates.

Reading this reference

  • Code in weft blocks is a complete template, and every one in this reference is parsed by the reference's own tests.
  • Code in text blocks is a fragment, such as a single expression.
  • The grammar collects the whole syntax in one place, and errors lists what the parser reports and how to fix it.