使用Golang模板需选择text/template或html/template,后者防XSS;通过Parse解析字符串模板,Execute渲染数据,支持嵌套字段、if/range控制结构;HTML模板自动转义恶意内容;可加载文件模板并用ParseGlob批量解析,ExecuteTemplate执行指定块。

在Golang中使用template渲染模板非常直接,主要通过标准库中的 text/template 和 html/template 实现。前者用于普通文本模板,后者专为HTML设计,具备自动转义功能,防止XSS攻击。
你可以通过字符串或文件定义模板,然后将数据注入其中进行渲染。
示例代码:
package main
<p>import (
"os"
"text/template"
)</p><p>func main() {
const templateStr = "Hello, {{.Name}}! You are {{.Age}} years old.\n"</p><pre class='brush:php;toolbar:false;'>// 定义数据结构
data := struct {
Name string
Age int
}{
Name: "Alice",
Age: 30,
}
// 解析模板
tmpl, err := template.New("greeting").Parse(templateStr)
if err != nil {
panic(err)
}
// 渲染到标准输出
err = tmpl.Execute(os.Stdout, data)
if err != nil {
panic(err)
}}
立即学习“go语言免费学习笔记(深入)”;
输出结果:
Hello, Alice! You are 30 years old.模板支持访问结构体的嵌套字段、使用if条件、range循环等控制结构。
示例:
const templateStr = `
{{if .User.LoggedIn}}
Welcome back, {{.User.Profile.Name}}!
{{range .User.Notifications}}
- {{.}}
{{end}}
{{else}}
Please log in.
{{end}}
`
对应的数据结构:
data := struct {
User struct {
LoggedIn bool
Profile struct{ Name string }
Notifications []string
}
}{
User: struct {
LoggedIn bool
Profile struct{ Name string }
Notifications []string
}{
LoggedIn: true,
Profile: struct{ Name string }{Name: "Bob"},
Notifications: []string{"New message", "Update available"},
},
}
如果你生成的是HTML内容,应使用 html/template,它会自动对数据进行HTML转义。
示例:
package main
<p>import (
"html/template"
"log"
"net/http"
)</p><p>func handler(w http.ResponseWriter, r *http.Request) {
tmpl := <code><h1>Hello, {{.}}</h1></code>
t, err := template.New("page").Parse(tmpl)
if err != nil {
log.Fatal(err)
}</p><pre class='brush:php;toolbar:false;'>// 即使输入包含HTML,也会被转义
t.Execute(w, "<script>alert('hack')</script>")}
立即学习“go语言免费学习笔记(深入)”;
func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }
浏览器中实际输出为:
<h1>Hello, <script>alert('hack')</script></h1>页面不会执行脚本,确保安全。
实际项目中模板通常存放在文件中。可以使用 template.ParseFiles 或 template.ParseGlob。
目录结构:
templates/ header.tmpl content.tmpl footer.tmpl加载多个模板文件:
t, err := template.ParseGlob("templates/*.tmpl")
if err != nil {
log.Fatal(err)
}
也可以定义可复用的块(block):
{{define "header"}}<html><body>{{end}}
{{define "content"}}<h1>Main Content</h1>{{end}}
{{define "footer"}}</body></html>{{end}}
执行特定块:
t.ExecuteTemplate(os.Stdout, "content", nil)
基本上就这些。掌握解析、数据绑定、控制结构和文件加载,就能灵活使用Go模板。关键是根据场景选择 text/template 还是 html/template,避免安全问题。
以上就是如何在Golang中使用template渲染模板的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号