Skip to content

Templates

Tuntii edited this page Dec 3, 2026 · 1 revision

Templates

Viltrum renders HTML pages from templates written in Mustache syntax. A template is parsed once, at startup; c.render fills it from a V value per request, HTML-escaping every field unless the template says otherwise, and writes the page straight into the response: no string is built and nothing is allocated per request.

import viltrum

struct Item {
	name  string
	price int
}

struct Page {
	title string
	items []Item
	empty bool
}

const page = viltrum.parse_template($embed_file('page.html').to_string()) or { panic(err) }

fn main() {
	mut app := viltrum.new()
	app.get('/', fn (mut c viltrum.Ctx) {
		c.render(200, page, Page{
			title: 'Shop'
			items: [Item{'Tea & cake', 4}, Item{'<Coffee>', 3}]
		})
	})
	app.listen(':8080')!
}

page.html:

<h1>{{title}}</h1>
<ul>
{{#items}}
  <li>{{name}}: {{price}}</li>
{{/items}}
</ul>
{{^items}}<p>Nothing yet.</p>{{/items}}

viltrum.template(path) reads the file at startup instead of embedding it. Both return an error for a tag that is not closed or a section closed out of order, so a broken template stops the server when it starts, not on a request.

Syntax

Tag Writes
{{name}} the field name of the current value, HTML-escaped (& < > " ')
{{{name}}}, {{& name}} the field as it is, unescaped
{{#name}}...{{/name}} an array: the block once per item, the item the current value inside. A struct: the block once, inside it. A bool, string or number: the block once when it is true, not empty or not zero
{{^name}}...{{/name}} the block once when name is false, empty or zero
{{.}} the current value itself (an array of strings or numbers)
{{! ...}} nothing: a comment

Strings, integers, floats and bools are written; a field of any other type writes nothing, and so does a name the current value has no field for. A section, closing or comment tag alone on its line removes that line from the output, as in Mustache, so blocks leave no blank lines.

Not supported

Names resolve in the current value only, not in the values around it (inside {{#items}}, {{title}} is the item's title, not the page's). Dotted names, partials, lambdas and delimiter changes are not supported.

API

Symbol Role
viltrum.template(path) !&Template read and parse a template file
viltrum.parse_template(text) !&Template parse a template's text ($embed_file)
c.render(status, t, value) answer with the page, text/html; charset=utf-8
t.render(mut out, value) append the page to a buffer

Clone this wiki locally