Go languagehtml/template
Modules are template engines designed for generating secure HTML output, supporting automatic escape to prevent XSS attacks. The following are the core methods and usage examples of this module:
1. Basic template analysis and rendering
and
Parses template strings and renders data.
package main import ( "html/template" "os" ) func main() { // Define template string tmplStr := `<h1>{{.Title}}</h1><p>{{.Content}}</p>` // parse template tmpl, err := ("page").Parse(tmplStr) if err != nil { panic(err) } // Define data data := struct { Title string Content string }{ Title: "Welcome Page", Content: "This is safely rendered!", } // Render and output to standard output err = (, data) if err != nil { panic(err) } }
Output result:
<h1>Welcome page</h1><p>This is what is safe to render!</p>
2. Load the template from the file
Load templates from multiple files, support template inheritance and nesting.
// File: templates/{{ define "header" }}<header>{{.SiteName}}</header>{{ end }} // File: templates/{{ define "page" }} <!DOCTYPE html> <html> {{ template "header" . }} <body> <h1>{{.Title}}</h1> </body> </html> {{ end }}
func main() { // parse multiple template files tmpl, err := ( "templates/", "templates/", ) if err != nil { panic(err) } // Render data data := struct { SiteName string Title string }{ SiteName: "My website", Title: "Homepage", } // Specify rendering using the "page" template err = (, "page", data) }
Output result:
<!DOCTYPE html> <html> <header>My website</header> <body> <h1>Home page</h1> </body> </html>
3. Automatic escape and secure content
Automatically escape XSS content
By default, all variable contents are escaped.
data := struct { UserInput string }{ UserInput: "<script>alert('xss')</script>", } tmplStr := `<div>{{.UserInput}}</div>` tmpl, _ := ("test").Parse(tmplStr) (, data)
Output result:
<div><script>alert('xss')</script></div>
Trust the original HTML
useType tag security content.
data := struct { SafeContent }{ SafeContent: ("<b>Bold text</b>"), } tmplStr := `<div>{{.SafeContent}}</div>` tmpl, _ := ("test").Parse(tmplStr) (, data)
Output result:
<div><b>Bold text</b></div>
4. Custom template functions
Funcs and
Register custom functions into the template.
func main() { // Define custom functions funcMap := { "safeHTML": func(s string) { return (s) }, } // Create templates and register functions tmplStr := `<div>{{. | safeHTML}}</div>` tmpl := ("test").Funcs(funcMap) tmpl, _ = (tmplStr) // Render data (, "<em>Italic text</em>") }
Output result:
<div><em>Italic text</em></div>
5. Conditional judgment and cycle
if and range grammar
Implement logical control in templates.
data := struct { ShowHeader bool Items []string }{ ShowHeader: true, Items: []string{"Go", "Python", "Java"}, } tmplStr := ` {{ if .ShowHeader }}<h1>List</h1>{{ end }} <ul> {{ range .Items }} <li>{{ . }}</li> {{ end }} </ul> ` tmpl, _ := ("list").Parse(tmplStr) (, data)
Output result:
<h1>List</h1> <ul> <li>Go</li> <li>Python</li> <li>Java</li> </ul>
6. Nested templates and block definitions
define and template directives
Reuse template fragments.
// Define the base templatetmplStr := ` {{ define "layout" }} <!DOCTYPE html> <html> <head>{{ template "title" }}</head> <body>{{ template "content" . }}</body> </html> {{ end }} {{ define "title" }}<title>Default title</title>{{ end }} {{ define "content" }}<p>Default content</p>{{ end }} ` // Cover some blockscustomTmplStr := ` {{ define "content" }}<h1>{{.Message}}</h1>{{ end }} ` // parse templatetmpl, _ := ("base").Parse(tmplStr) tmpl, _ = (customTmplStr) // Render datadata := struct{ Message string }{Message: "Custom content"} (, "layout", data)
Output result:
<!DOCTYPE html> <html> <head><title>Default title</title></head> <body><h1>Custom content</h1></body> </html>
Summarize
- Security: Automatically escape HTML special characters to prevent XSS attacks.
-
Core Methods:
Parse
,ParseFiles
,Execute
,Funcs
。 -
Advanced features:
- Nested templates (
define
andtemplate
)。 - Conditions and loops (
if
、range
)。 - Custom functions (
Funcs
)。
- Nested templates (
- Applicable scenarios: Dynamically generate secure HTML pages, such as backend rendering of web applications.
This is the article about the detailed function introduction and sample code of the html/template module in Go language. For more related content of the html/template module, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!