Tern

html

The html module escapes text for HTML and renders templates that escape by default: a value printed with {{name}} can't inject markup, however it was typed. A template renders a JSON value, the output of json.encode, so any struct, map or array can feed one.

import html
import json

struct Item:
    name: str
    price: str

struct Cart:
    owner: str
    items: [Item]

fn main():
    cart = Cart("Ada <admin>", [Item("Tea & biscuits", "3.50"), Item("<script>", "0.00")])
    t = "<h1>{{owner}}'s cart</h1><ul>{{#each items}}<li>{{name}}: {{price}}</li>{{/each}}</ul>"
    print(html.render(t, json.encode(cart)))
Output
<h1>Ada &lt;admin&gt;'s cart</h1><ul><li>Tea &amp; biscuits: 3.50</li><li>&lt;script&gt;: 0.00</li></ul>

Functions

fn escape(s: str) str                    & < > " ' as entities
fn render(template: str, data: str) str  data: JSON, usually json.encode(value)
fn render_file(path: str, data: str) str
fn error() str

render_file reads a template file, parses it once and keeps it (a changed file is read again), and lets it include others with {{> header.html}}, relative to its own directory. A template with a mistake (an unclosed block, {{else}} outside {{#if}}, a missing file) renders as "", and html.error() says what and where ("line 3: {{#...}} is never closed"); after a success it's "".

Templates

TagDoes
{{name}}, {{user.name}}the value, HTML-escaped; null or a missing name prints nothing
{{.}}the current element inside {{#each}}
{{{name}}}the value as it is: only for HTML you made or trust
{{json name}}the value as JSON, for <script> (with <, >, & escaped as < ...)
{{#each items}} ... {{/each}}the block once per array element (or object value); {{@index}} counts from 0
{{#if x}} ... {{else}} ... {{/if}}x counts as false if it's false, null, 0, "", [] or {}
{{#unless x}} ... {{/unless}}the opposite
{{> file.html}}another template file (with render_file)
{{! note }}a comment

Inside {{#each}}, a name is looked up in the element first and then in the enclosing data, so an item's template can still reach page-level values:

import html

fn main():
    data = `{"currency":"EUR","items":[{"name":"tea","price":3},{"name":"cake","price":4,"currency":"GBP"}]}`
    print(html.render("{{#each items}}{{@index}}. {{name}} {{price}} {{currency}}\n{{/each}}", data))
    print(html.render("{{#if items}}{{#unless empty}}has items{{/unless}}{{else}}none{{/if}}", data))
Output
0. tea 3 EUR
1. cake 4 GBP

has items

With the web module, render a page and send it with roost.html:

Compiles (not run here)
import html
import json
import roost

struct Profile:
    name: str
    bio: str

fn profile(req: roost.Request) roost.Response:
    p = Profile(req.param("name"), "Writes <b>programs</b>.")
    page = html.render_file("templates/profile.html", json.encode(p))
    if page == "":
        return roost.status(500, html.error())
    return roost.html(page)

fn main():
    r = roost.router()
    r.get("/u/{name}", profile)
    roost.serve(r, 8080)

Escaping makes values safe inside element content and quoted attribute values (title="{{x}}"). It doesn't make a URL safe inside href="{{link}}" (a javascript: URL stays one), or text safe inside <script> other than through {{json}}: check URLs that come from users before putting them in links.

With Result

try_render(template, data) and try_render_file(path, data) return Result[str, str], so a handler can write page = html.try_render_file(path, json.encode(v))? in a helper that returns a Result, and map the Err ("html: render failed: line 3: ...") to a 500.

Speed and memory

bench/std does the same work with Go's html/template and Rust's handlebars crate (the same template syntax): a page of 1,000 users rendered from the program's structs (here json.encode, then render), a one-line template, and escaping 1 MB of text.

TernGoRust
page of 1,000 rows398 us3,389 us1,893 us
one-line template264 ns840 ns372 ns
escape1,418 MB/s662 MB/s672 MB/s
peak memory5.6 MB23.9 MB7.9 MB

The data is parsed into flat arrays (strings stay in the JSON text unless they have escapes), and escaping finds the bytes to replace 16 at a time. Template files are parsed once and kept until they change.

Source: docs/std/html.md. Every example on this page is compiled and run by tern x test docs.