Unlike the text/html package in Go, the html/template package cleans the data and escapes all inputs before running it on the client side. This prevents security flaws such code injection using Cross Site Scripting.
Components of a Template
A template is made up of three main components.
Actions
Data evaluations refer to functions, loops, and data evaluations. They are denoted by the use of double curly braces as {{.}} A dot element inside a template represents the root element. Using template actions, you can determine the final output based on a specific expression.
Conditions
You can also include if…else constructs in a template. An example of if…else check in a template is as shown:
The above syntax will run the first block if the first condition is true, otherwise, check condition 2 and if true, run the second block. If none are true, run the else block.
Loops
Loops are also supported inside a template. For example, you can iterate over a slice inside a template as shown:
The var can be any iterable type such as an array, slice, or map.
Golang HMTL Template
Working with templates in HTML is very straightforward. You can use the template constructs discussed above to determine how you can insert the data.
For example, we can create a list and iterate over each element on the list. We can then pass that information to html template to display the actual on the client side.
An example is as shown below:
import (
"html/template"
"log"
"os"
)
type Users struct {
Username string
Expired bool
}
type Info struct {
SiteTitle string
Data []Users
}
func main() {
var temp = `
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{.SiteTitle}}</title>
</head>
<body>
<h1>
<ul>
{{range. data}}
{{if .expired}}
<li>{{.item}}</li>
{{else}}
<li>{{.item}}</li>
</ul>
</h1>
</body>
</html>`
// parse template
t, err := template.New("users").Parse(temp)
if err != nil {
log.Fatal(err)
}
data := Info{
SiteTitle: "HTML Templating",
Data: []Users{
{Username: "username1", Expired: true},
{Username: "username2", Expired: false},
},
}
t.Execute(os.Stdout, data)
}
The above examples use html/template to inject data from the struct to the html template.
Closing
This guide illustrates how to use html/template package to inject dynamic content into HTML file. Check out the html/template package to learn more.