In this comprehensive chapter, we'll explore templating in Go using the built-in html/template and text/template packages. Templating is a powerful technique used to generate dynamic HTML or text content by combining template files with data. We'll start with the basics of templating and gradually delve into more advanced topics, covering everything you need to know to effectively use templates in your Go applications.
Templating is the process of creating reusable structures or templates that contain placeholders for dynamic content. These placeholders are replaced with actual data when the template is executed, generating the final output.
text/template
The text/template
package provides functionality for parsing and executing text templates. Text templates are suitable for generating plain text or non-HTML content.
package main
import (
"os"
"text/template"
)
func main() {
const tpl = "Hello, {{.Name}}!"
t := template.Must(template.New("text").Parse(tpl))
data := struct {
Name string
}{
Name: "John",
}
err := t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
{{.Placeholder}}
syntax.template.New().Parse()
.t.Execute()
.html/template
The html/template
package extends the functionality of text/template
to generate HTML content safely. It automatically escapes data to prevent cross-site scripting (XSS) attacks.
package main
import (
"os"
"html/template"
)
func main() {
const tpl = "Hello, {{.Name}}!
"
t := template.Must(template.New("html").Parse(tpl))
data := struct {
Name string
}{
Name: "",
}
err := t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
template.Must()
to create the template and panic if there’s an error.
package main
import (
"os"
"html/template"
"strings"
)
func main() {
const tpl = "Hello, {{ToLower .Name}}!"
t := template.Must(template.New("advanced").Funcs(template.FuncMap{
"ToLower": strings.ToLower,
}).Parse(tpl))
data := struct {
Name string
}{
Name: "JOHN",
}
err := t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
template.FuncMap
.Template inheritance allows you to define a base template with common elements shared across multiple pages and extend or override specific sections in child templates.
{{block "title" .}}{{end}} - My Website
{{block "content" .}}{{end}}
In this chapter, we've covered the fundamentals of templating in Go using the html/template and text/template packages. From basic template creation and execution to advanced techniques like using template functions and template inheritance, you now have a comprehensive understanding of how to leverage templating in your Go applications. Experiment with different template structures and techniques to create dynamic and visually appealing content for your web applications. Happy templating !❤️