Go语言通过html/template包实现模板渲染,先定义含变量和逻辑的HTML模板文件,再用template.ParseFiles加载并Execute执行,结合net/http生成动态网页。

Go语言通过 html/template 包提供了强大的模板引擎,可以用来渲染动态网页。你只需要定义HTML模板文件,在其中插入变量和逻辑控制结构,然后在Go程序中传入数据并执行渲染即可。
准备模板文件
在项目目录下创建一个 templates 文件夹,并添加一个HTML模板文件,比如 index.html:
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head><title>用户信息</title></head>
<body>
<h1>欢迎,{{.Name}}!</h1>
<p>你的邮箱是:{{.Email}}</p>
{{if .IsAdmin}}
<p><strong>你是管理员</strong></p>
{{else}}
<p>你是普通用户</p>
{{end}}
<h2>权限列表:</h2>
<ul>
{{range .Roles}}
<li>{{.}}</li>
{{end}}
</ul>
</body>
</html>
在Go中加载并渲染模板
使用 template.ParseFiles 加载模板文件,然后调用 Execute 方法传入数据进行渲染。
立即学习“go语言免费学习笔记(深入)”;
示例代码:
package main
import (
"net/http"
"log"
"html/template"
)
type User struct {
Name string
Email string
IsAdmin bool
Roles []string
}
func main() {
tpl := template.Must(template.ParseFiles("templates/index.html"))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
user := User{
Name: "张三",
Email: "zhangsan@example.com",
IsAdmin: true,
Roles: []string{"read", "write", "delete"},
}
tpl.Execute(w, user)
})
log.Println("服务器启动在 :8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
模板语法说明
Go模板支持多种语法来实现动态内容:
- {{.FieldName}}:访问结构体字段或变量值
- {{if .Condition}}...{{else}}...{{end}}:条件判断
- {{range .Slice}}...{{end}}:遍历数组、切片或map
- {{with .Value}}...{{end}}:设置当前作用域对象
注意:Go模板会自动对输出进行HTML转义,防止XSS攻击。如果需要输出原始HTML,使用 template.HTML 类型。
多个模板与复用
你可以使用 template.ParseGlob 加载多个模板,或者通过 define 和 template 指令实现模板复用。
例如,在模板中定义一个可复用的头部:
{{define "header"}}
<h2>网站标题</h2>
{{end}}
在主模板中引入:
{{template "header"}}
基本上就这些。Go的模板系统简单但足够应对大多数Web页面渲染需求,结合 net/http 使用非常方便。只要组织好数据结构,就能轻松生成动态HTML页面。










