template
Filling text and HTML templates with values, with automatic escaping for safety.
import template
On this page
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.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")
endOutputHello Sara! <hello>
<p><hello></p>
<a href="x">&</a>
{{name}}
EscapeHTML
func EscapeHTML(s: str): strEscapes 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>): strFills 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>): strLike
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): strBuilds 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