Building
Views and fragments
Templ components, the difference between pages and fragments, and how escaping works.
Components
A component is a Go function that returns a templ.Component. Write it in a .templ file, then run templ generate, which writes a *_templ.go file. Never edit the generated file: when a page looks stale, the generated file is almost always out of date.
templ Greeting(text string) {
<h2 id="greeting">{ text }</h2>
}Templ escapes text, attributes and URLs by their context. Hostile input such as <script> is shown as text. Avoid templ.Raw, templ.SafeURL and inline scripts that carry user data.
Pages and fragments
A page wraps itself in Layout, which holds the document head, the scripts, the CSRF token for htmx, and the toast container. A fragment is what htmx swaps into the page, so it never renders the layout. Keep a stable id on every swap target.
Out-of-band toasts are the one place a response changes something other than its target: a toast carries hx-swap-oob="beforeend:#toasts", and the layout's container receives it.
Was this page helpful?
Be the first to answer.