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
putthem. - Values are inserted as they are and never scanned again, so a value that contains
{{cannot inject a tag. RenderHTMLescapes& < > " '. 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 asjavascript:...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.
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)
endConditions 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.
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", "")
endSafe 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.
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)
endThe 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.
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| Job | Use |
|---|---|
| Email, plain text, a config file | Render |
| HTML with values from users | RenderHTML |
| Putting already built HTML into a layout | Render |
| Escaping one value by hand | EscapeHTML |
| Writing a placeholder from code | Var |
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>put and free it when you are done.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")
endEscapeHTML
func EscapeHTML(s: str): strThe example for this item is shown with the ones above: template-Render.salam
Render
func Render(tmpl: str, ctx: HashMap<str, str>): str{{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>): strRender, 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{{name}}. Useful when you are building the template in code.The example for this item is shown with the ones above: template-Render.salam