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

在 Go 语言中,
html/template
包是处理 HTML 模板渲染的核心工具。它不仅安全(自动转义防止 XSS 攻击),而且功能强大,适合构建动态网页内容。下面详细介绍如何使用
template
包来渲染 HTML 页面。
一、基本用法:定义模板并渲染数据
html/template
的核心是将结构化数据注入到 HTML 模板中,生成最终的 HTML 输出。
package mainimport ( "html/template" "log" "os")type User struct { Name string Email string}func main() { // 定义模板字符串 const tmpl = `Hello, {{.Name}}!
Email: {{.Email}}
立即学习“go语言免费学习笔记(深入)”;
` // 解析模板 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) }}
输出结果:
Hello, Alice!
Email: alice@example.com
注意:使用 html/template 而不是 text/template,因为前者会对输出自动进行 HTML 转义,防止 XSS。
二、加载外部 HTML 文件模板
通常模板会写在
.html
文件中,便于维护。
假设有一个
templates/index.html
:
User Info Welcome, {{.Name}}!
Your email is: {{.Email}}
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
简化错误处理
template.Must
是一个辅助函数,用于包装
Parse
或
ParseFiles
,如果解析失败会直接 panic。
t := template.Must(template.ParseFiles("templates/index.html"))t.Execute(os.Stdout, user)
适用于开发阶段或确定模板文件一定存在的情况。
四、模板语法详解
1. 数据引用
{{.}}
:表示当前上下文的数据
{{.FieldName}}
:访问结构体字段(必须是导出字段,首字母大写)
{{.Field.Nested}}
:支持嵌套结构
type Profile struct { User User Age int Hobbies []string}
模板中:
Age: {{.Age}}
Hobbies: {{range .Hobbies}}{{.}}{{end}}
2. 控制结构
if 判断:
{{if .Email}} Email: {{.Email}}
立即学习“go语言免费学习笔记(深入)”;
{{else}} No email provided.
{{end}}
range 遍历:
- {{range .Hobbies}}
- {{.}} {{end}}
with:切换上下文
{{with .User}} {{.Name}}
{{end}}
3. 变量定义(以
$
$
开头)
{{ $email := .Email }}Contact: {{$email}}
可以在
range
中避免变量覆盖时使用。
五、模板嵌套与复用:
define
define
和
template
可以定义多个命名模板,并在主模板中嵌套使用。
例如
layout.html
:
{{define "header"}}{{.Title}} {{end}}{{define "footer"}}{{end}}
page.html
:
{{template "header" .}}{{.Content}}
{{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
你可以向模板中注入自定义函数,比如格式化时间、转大写等。
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}}")
使用管道
|
调用函数。
七、常见陷阱与注意事项
字段必须可导出:模板只能访问结构体中首字母大写的字段。自动转义:HTML、JS、URL 等内容会被自动转义。若要输出原始 HTML,使用
template.HTML
类型:
type Data struct { Content template.HTML}data := Data{Content: template.HTML("Bold text")}
否则
会被转义成
。
模板缓存:生产环境建议预解析模板,避免每次请求都解析。错误处理:模板执行错误(如字段不存在)会返回错误,需检查
Execute
返回值。
八、结合 HTTP 服务使用
在 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
包后,你可以在不引入前端框架的情况下,用 Go 构建简单的动态网页应用。关键是理解数据传递、模板语法和安全转义机制。
以上就是如何用Golang渲染HTML模板 详解template包的用法的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1400227.html
微信扫一扫
支付宝扫一扫