Understanding Go's html/template Package for Secure HTML Generation
The html/template package in Go provides a data-driven template engine specifically designed to produce HTML output that is safe from code injection, such as cross-site scripting (XSS). It shares the same interface as text/template, but automatically escapes any potentially dangerous code. For any scenario where HTML is generated in Go, html/template is the recommended choice over text/template.
Template Fundamentals
- Template files conventionally use the
.tmplor.tplextension (though others work), and must be UTF-8 encoded. - Dynamic data is inserted using the
{{and}}delimiters. - Template data is accessed via the dot (
.). For complex types, use{{ .FieldName }}to access exported fields. - Anything outside the
{{and}}delimiters is output verbatim. - The workflow consists of three steps:
- Define a template.
- Parse the template file(s).
- Execute (render) the template with data.
Basic Example
Template file (hello.tmpl)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
<p>hello {{ . }}</p>
</body>
</html>
Go server code
package main
import (
"net/http"
"html/template"
)
func hello(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("template/hello.tmpl")
if err != nil {
return
}
name := "hello"
err = t.Execute(w, name)
if err != nil {
return
}
}
func main() {
http.HandleFunc("/", hello)
err := http.ListenAndServe(":9090", nil)
if err != nil {
return
}
}
Passing Maps and Structs
Map data
Server:
m1 := map[string]interface{}{
"name": "ll",
"gender": "female",
"age": 0,
}
Template:
<p>hello {{ .name }}</p>
<p>hello {{ .age }}</p>
<p>hello {{ .gender }}</p>
Struct data (exported fields only)
Server:
type User struct {
Name string
Gender string
Age int
}
u1 := User{
Name: "ll",
Gender: "female",
Age: 0,
}
Template:
<p>hello {{ .Name }}</p>
<p>hello {{ .Age }}</p>
<p>hello {{ .Gender }}</p>
Multiple parameters via a wrapping map
Server:
u1 := User{
Name: "struct_para",
Gender: "female",
Age: 0,
}
m1 := map[string]interface{}{
"name": "map_para",
"gender": "female",
"age": 0,
}
_ = t.Execute(w, map[string]interface{}{
"struct": u1,
"map_itf": m1,
})
Template:
<p>hello {{ .struct.Name }}</p>
<p>hello {{ .map_itf.name }}</p>
Variables and Whitespace
Variables
{{$v := 114}}
{{$v}}
Trimming whitespace
Use {{- and -}} to trim surrounding whitespace:
{{- .name -}}
Control Structures
Conditionals
{{ $v1 := 114 }}
{{if $v1}}
{{$v1}}
{{else}}
Nothing
{{end}}
Range (iteration)
{{range $idx, $hobby := .hobby}}
<p>{{$idx}} - {{$hobby}}</p>
{{else}}
empty
{{end}}
With (scoping)
Shortens the scope so that . refers to a specific sub-value:
{{with .struct}}
<p>hello {{ .Name }}</p>
<p>hello {{ .Age }}</p>
<p>hello {{ .Gender }}</p>
{{end}}
Predefined Functions
| Function | Description |
|---|---|
and |
Returns the first empty argument or the last argument. and x y is equivalent to if x then y else x. All arguments are evaluated. |
or |
Returns the first non-empty argument or the last argument. or x y is equivalent to if x then x else y. All arguments are evaluated. |
not |
Returns the Boolean negation of its single argument. |
len |
Returns the integer length of its argument. |
index |
Returns the result of indexing its first argument by the subsequent arguments. Example: index x 1 2 3 returns x[1][2][3]. The indexed value must be an array, slice, or map. |
print |
Alias for fmt.Sprint. |
printf |
Alias for fmt.Sprintf. |
println |
Alias for fmt.Sprintln. |
html |
Returns escaped HTML equivalent of its argument's textual representation. Not available in html/template (auto-escaped). |
urlquery |
Returns escaped value suitable for embedding in a URL query. Not available in html/template. |
js |
Returns escaped JavaScript equivalent of its argument's textual representation. |
call |
Calls the first argument, which must be a function, with the remaining arguments as parameters. Example: call .X.Y 1 2 is equivalent to dot.X.Y(1, 2). The function must return either one value or two values where the second is error. If the error is non-nil, execution halts and the error is returned to the caller. |
Comparison Functions
All comparison functions return a Boolean:
| Function | Returns true if |
|---|---|
eq |
arg1 == arg2 |
ne |
arg1 != arg2 |
lt |
arg1 < arg2 |
le |
arg1 <= arg2 |
gt |
arg1 > arg2 |
ge |
arg1 >= arg2 |
Custom Functions
You can register custom functions via template.FuncMap:
Server:
lenFunc := func(str string) (int, error) {
return len(str), nil
}
t := template.New("").Funcs(template.FuncMap{"len": lenFunc})
Template usage:
<p>hello {{ len .struct.Name }}</p>
Template Nesting
Inline defined template (inside main template)
Main template (hello.tmpl):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>hello</title>
</head>
<body>
{{template "a.tmpl"}}
{{template "b.tmpl"}}
</body>
</html>
{{define "a.tmpl"}}
<a>
<li>test_a_tmpl</li>
</a>
{{end}}
External template file (b.tmpl)
<b>
<li>test_b_tmpl</li>
</b>
Server:
package main
import (
"html/template"
"net/http"
)
func hello(w http.ResponseWriter, r *http.Request) {
// ParseFiles with the main template first, then the nested one
t, err := template.ParseFiles("template/hello.tmpl", "template/b.tmpl")
if err != nil {
return
}
_ = t.Execute(w, nil)
}
func main() {
http.HandleFunc("/", hello)
_ = http.ListenAndServe(":9090", nil)
}
Block Action (Template Inheritance)
The block action defines a default template that can be overridden by another template with the same name.
Base template (base.tmpl)
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{ . }}</title>
<style>
*{ margin:0; }
.nav{ height:50px; width:100%; position:fixed; top:0; background-color:yellow; }
.main{ margin-top:50px; }
.context{ width:20%; height:100%; position:fixed; left:0; background-color:blue; }
.center { text-align:center; }
</style>
</head>
<body>
<div class="nav"></div>
<div class="main">
<div class="menu"></div>
<div class="context center">
{{block "content" .}}{{end}}
</div>
</div>
</body>
</html>
Child template (test_home.tmpl)
{{template "base.tmpl"}}
{{define "content"}}
<h1>home_page</h1>
{{end}}
Server (parse base first, then child):
func home2(w http.ResponseWriter, r *http.Request) {
t, err := template.ParseFiles("template/base.tmpl", "template/test_home.tmpl")
if err != nil {
return
}
_ = t.Execute(w, "home")
}
Custom Delimiters
To avoid conflicts with other languages (e.g., Angular, Vue), you can change the default {{ }} delimiters:
Server:
func test(w http.ResponseWriter, r *http.Request) {
t, err := template.New("test.tmpl").
Delims("{[", "]}").
ParseFiles("template/test.tmpl")
if err != nil {
return
}
_ = t.Execute(w, nil)
}
The template then uses {[ name ]} instead of {{ name }}.
Integration with Gin Framework
Gin provides convenience methods for loading and rendering templates.
Main server setup
package main
import (
"github.com/gin-gonic/gin"
"html/template"
"net/http"
)
func main() {
r := gin.Default()
r.Static("/name", "statics")
// Register custom functions before template parsing
r.SetFuncMap(template.FuncMap{
"safe": func(str string) template.HTML {
return template.HTML(str)
},
})
// Load all templates recursively
r.LoadHTMLGlob("templates/**/*")
r.GET("/users/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "moreac.top",
})
})
r.GET("/posts/index", func(ctx *gin.Context) {
ctx.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "moreac.top",
})
})
_ = r.Run(":9090")
}
Example template (templates/posts/index.tmpl)
{{define "posts/index.tmpl"}}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>posts/index</title>
</head>
<body>
{{ .title }}
</body>
</html>
{{end}}
Static File Handling
When your HTML references CSS, JavaScript, or images, you need to serve them as static files. In Gin, the r.Static("/url-path", "local-directory") call does this. The example above maps the /name URL path to the statics local directory.