Standard library · Text

template

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

import template

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.

Use it for emails, notifications, generated configuration files and small HTML fragments. For whole web pages with components and styles, the layout language of Salam is the better tool; for formatting numbers and dates into a sentence, fmt is shorter.

What the language has, and what it does not

  • Only three tags: {{name}}, {{#if name}} with an optional {{else}} and a closing {{/if}}, and the comment {{! ... }}. There are no loops, filters or dotted paths: build repeated parts in Salam and put the result in the context, as the HTML example does.
  • The context holds only strings. Turn numbers and bools into text before you put them.
  • Values are inserted as they are and never scanned again, so a value that contains {{ cannot inject a tag.
  • RenderHTML escapes & < > " '. That makes a value safe as page text and inside a quoted attribute, but not inside a <script> block or as a link address: a value such as javascript:... passes through unchanged.

Fill a plain text message

The common job is a message with a few names in it: an email, a notification or a receipt. Put every value in the context with put, then call Render. The same context can be filled again and rendered a second time, so one template serves every customer. A section wrapped in {{#if key}} ... {{/if}} appears only when the key has a value, and {{! ... }} is a comment that never reaches the output.

template-guide-email.salam
import template

func main:
    letter := "Hello {{name}},\n\nYour order {{order}} has shipped.\n{{#if tracking}}Track it here: {{tracking}}\n{{/if}}{{! the tracking line is optional }}\nThanks,\n{{shop}}"

    mut ctx := template.NewContext()
    defer ctx.Free()
    ctx.Put("name", "Sara")
    ctx.Put("order", "#1042")
    ctx.Put("tracking", "https://post.example/T-77")
    ctx.Put("shop", "Kooche Books")
    println template.Render(letter, ctx)
    println "-----"
    ctx.Put("name", "Reza")
    ctx.Put("order", "#1043")
    ctx.Put("tracking", "")
    println template.Render(letter, ctx)
end
OutputHello Sara, Your order #1042 has shipped. Track it here: https://post.example/T-77 Thanks, Kooche Books ----- Hello Reza, Your order #1043 has shipped. Thanks, Kooche Books

Conditions and else

{{#if key}} takes an optional {{else}} branch, and the blocks can be nested. A key counts as false when it is missing, empty, "false" or "0"; any other text, such as "yes" or "3", counts as true. The context only holds strings, so a number or a bool has to be turned into text first, for example with str.FromInt.

template-guide-conditions.salam
import template

func badge(user: str, admin: str, unread: str): str:
    mut ctx := template.NewContext()
    defer ctx.Free()
    ctx.Put("user", user)
    ctx.Put("admin", admin)
    ctx.Put("unread", unread)
    ret template.Render("{{user}}{{#if admin}} [admin]{{/if}}: {{#if unread}}{{unread}} new{{else}}no new{{/if}} messages", ctx)
end

func main:
    println badge("sara", "true", "3")
    println badge("reza", "false", "0")
    println badge("mina", "", "12")
    println badge("ali", "yes", "")
end
Outputsara [admin]: 3 new messages reza: no new messages mina: 12 new messages ali [admin]: no new messages

Safe HTML from user data

A page is usually built from small pieces. Render each row with RenderHTML, so that whatever a visitor typed is escaped, and then place the finished rows into the outer layout with Render. If you used RenderHTML for the outer step too, the rows would be escaped a second time and the browser would show the tags as text.

template-guide-page.salam
import template

struct Book:
    pub title: str = ""
    pub author: str = ""
end

func main:
    mut books := Vector {} as Vector<Book>
    defer books.Free()
    books.Push(Book { title = "Salt & Ink", author = "N. Karimi" })
    books.Push(Book { title = "<script>alert(1)</script>", author = "a visitor" })

    row := "<li>{{title}} by {{author}}</li>\n"
    mut rows := ""
    mut item := template.NewContext()
    defer item.Free()
    each book in books:
        item.Put("title", book.title)
        item.Put("author", book.author)
        rows += template.RenderHTML(row, item)
    end

    mut page := template.NewContext()
    defer page.Free()
    page.Put("heading", "New books")
    page.Put("items", rows)
    layout_text := "<h1>{{heading}}</h1>\n<ul>\n{{items}}</ul>"
    println template.Render(layout_text, page)
end
Output<h1>New books</h1> <ul> <li>Salt &amp; Ink by N. Karimi</li> <li>&lt;script&gt;alert(1)&lt;/script&gt; by a visitor</li> </ul>

The rule to remember: escape a value exactly once, at the moment it is put into HTML. Text that you already escaped, or HTML that your own program built, goes in with Render.

Configuration files and edge cases

Templates are not only for HTML. A configuration file, a SQL migration header or a shell script can be generated the same way, and Var builds the placeholder when the template itself is put together in code. A key that is missing from the context is replaced with nothing, not with an error, and a {{ without its closing braces is copied as it is.

template-guide-config.salam
import template

func render_site(name: str, port: str, tls: str): str:
    mut ctx := template.NewContext()
    defer ctx.Free()
    ctx.Put("name", name)
    ctx.Put("port", port)
    ctx.Put("tls", tls)
    mut conf := "server {\n"
    conf = conf + "    server_name " + template.Var("name") + ";\n"
    conf += "    listen {{port}}{{#if tls}} ssl{{/if}};\n"
    conf += "    root /srv/{{name}}/public;\n}"
    ret template.Render(conf, ctx)
end

func main:
    println render_site("blog.example", "443", "on")
    println render_site("intranet.local", "8080", "")
    mut empty := template.NewContext()
    defer empty.Free()
    println "[" + template.Render("{{missing}}", empty) + "]"
    println template.Render("left {{open", empty)
end
Outputserver { server_name blog.example; listen 443 ssl; root /srv/blog.example/public; } server { server_name intranet.local; listen 8080; root /srv/intranet.local/public; } [] left {{open
JobUse
Email, plain text, a config fileRender
HTML with values from usersRenderHTML
Putting already built HTML into a layoutRender
Escaping one value by handEscapeHTML
Writing a placeholder from codeVar

Because a missing key renders as empty text, a typo in a key name fails silently. When a value is required, check it with has on the context before rendering. For full HTML pages with components and styles, look at the layout language instead; this package is for filling text.

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