在 go 语言中,html/template 包用于安全地渲染 html 模板,防止 xss 攻击,其核心用法包括定义模板、解析文件、嵌套复用、自定义函数及结合 http 服务输出动态内容,必须使用导出字段并注意自动转义机制,最终通过 execute 或 executetemplate 方法将数据注入模板并完整输出 html 内容。

在 Go 语言中,
html/template
template
html/template
package main
import (
"html/template"
"log"
"os"
)
type User struct {
Name string
Email string
}
func main() {
// 定义模板字符串
const tmpl = `<h1>Hello, {{.Name}}!</h1><p>Email: {{.Email}}</p>`
// 解析模板
t, err := template.New("user").Parse(tmpl)
if err != nil {
log.Fatal(err)
}
// 准备数据
user := User{Name: "Alice", Email: "alice@example.com"}
// 渲染模板到标准输出
err = t.Execute(os.Stdout, user)
if err != nil {
log.Fatal(err)
}
}输出结果:
立即学习“go语言免费学习笔记(深入)”;
<h1>Hello, Alice!</h1><p>Email: alice@example.com</p>
注意:使用 html/template 而不是 text/template,因为前者会对输出自动进行 HTML 转义,防止 XSS。
通常模板会写在
.html
假设有一个
templates/index.html
<!DOCTYPE html>
<html>
<head><title>User Info</title></head>
<body>
<h1>Welcome, {{.Name}}!</h1>
<p>Your email is: {{.Email}}</p>
</body>
</html>Go 代码加载并渲染:
t, err := template.ParseFiles("templates/index.html")
if err != nil {
log.Fatal(err)
}
user := User{Name: "Bob", Email: "bob@example.com"}
t.Execute(os.Stdout, user)也可以一次加载多个模板文件:
template.ParseFiles("header.html", "footer.html", "index.html")template.Must
template.Must
Parse
ParseFiles
t := template.Must(template.ParseFiles("templates/index.html"))
t.Execute(os.Stdout, user)适用于开发阶段或确定模板文件一定存在的情况。
{{.}}{{.FieldName}}{{.Field.Nested}}type Profile struct {
User User
Age int
Hobbies []string
}模板中:
<p>Age: {{.Age}}</p>
<p>Hobbies: {{range .Hobbies}}<span>{{.}}</span>{{end}}</p>if 判断:
{{if .Email}}
<p>Email: {{.Email}}</p>
{{else}}
<p>No email provided.</p>
{{end}}range 遍历:
<ul>
{{range .Hobbies}}
<li>{{.}}</li>
{{end}}
</ul>with:切换上下文
{{with .User}}
<h2>{{.Name}}</h2>
{{end}}$
{{ $email := .Email }}
<p>Contact: {{$email}}</p>可以在
range
define
template
可以定义多个命名模板,并在主模板中嵌套使用。
例如
layout.html
{{define "header"}}
<html><head><title>{{.Title}}</title></head><body>
{{end}}
{{define "footer"}}
</body></html>
{{end}}page.html
{{template "header" .}}
<h1>{{.Content}}</h1>
{{template "footer" .}}Go 代码:
t := template.Must(template.ParseFiles("layout.html", "page.html"))
data := map[string]string{
"Title": "My Page",
"Content": "Hello World",
}
t.ExecuteTemplate(os.Stdout, "page.html", data)可以指定执行某个命名模板。ExecuteTemplate登录后复制
FuncMap
你可以向模板中注入自定义函数,比如格式化时间、转大写等。
funcMap := template.FuncMap{
"upper": strings.ToUpper,
"formatDate": func(t time.Time) string {
return t.Format("2006-01-02")
},
}
t := template.New("demo").Funcs(funcMap)
t, err := t.Parse("Name: {{.Name | upper}}")使用管道
|
template.HTML
type Data struct {
Content template.HTML
}
data := Data{Content: template.HTML("<b>Bold text</b>")}否则
<b>
<b>
Execute
在 Web 应用中,通常配合
net/http
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
t := template.Must(template.ParseFiles("templates/index.html"))
user := User{Name: "Alice", Email: "alice@example.com"}
t.Execute(w, user)
})
http.ListenAndServe(":8080", nil)基本上就这些核心用法。掌握
html/template
以上就是如何用Golang渲染HTML模板 详解template包的用法的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号