Standard library · Text

template

Filling text and HTML templates with values, with automatic escaping for safety.

import template
On this page
  1. Functions

A template is text with holes in it; every {{name}} is filled with the value of that name from a "context". A context is a map from name to value.

If the output is HTML and the values came from a user, always use RenderHTML. It escapes the dangerous characters such as <, so that nobody can inject code into your page. This website is built with this package.

Functions

NewContext

func NewContext(): HashMap<str, str>
Creates an empty context: a map from name to value. Add values with put and free it when you are done.
template-Render.salam
import template

func main:
    mut ctx := template.NewContext()
    defer ctx.free()
    ctx.put("name", "Sara")
    ctx.put("message", "<hello>")
    println template.Render("Hello {{name}}! {{message}}", ctx)
    println template.RenderHTML("<p>{{message}}</p>", ctx)
    println template.EscapeHTML("<a href=\"x\">&</a>")
    println template.Var("name")
end
OutputHello Sara! <hello> <p>&lt;hello&gt;</p> &lt;a href=&quot;x&quot;&gt;&amp;&lt;/a&gt; {{name}}

EscapeHTML

func EscapeHTML(s: str): str
Escapes the special HTML characters so the text is shown exactly as written.

The example for this item is shown with the ones above: template-Render.salam

Render

func Render(tmpl: str, ctx: HashMap<str, str>): str
Fills every {{name}} in the template from the context, with no escaping at all. For plain text, email or a configuration file.

The example for this item is shown with the ones above: template-Render.salam

RenderHTML

func RenderHTML(tmpl: str, ctx: HashMap<str, str>): str
Like Render, but escapes every value for HTML before placing it.

The example for this item is shown with the ones above: template-Render.salam

Var

func Var(name: str): str
Builds the placeholder for a name, that is, {{name}}. Useful when you are building the template in code.

The example for this item is shown with the ones above: template-Render.salam