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>
使用 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模板支持多种语法来实现动态内容:
注意:Go模板会自动对输出进行HTML转义,防止XSS攻击。如果需要输出原始HTML,使用 template.HTML 类型。
你可以使用 template.ParseGlob 加载多个模板,或者通过 define 和 template 指令实现模板复用。
例如,在模板中定义一个可复用的头部:
{{define "header"}}
<h2>网站标题</h2>
{{end}}
在主模板中引入:
{{template "header"}}
基本上就这些。Go的模板系统简单但足够应对大多数Web页面渲染需求,结合 net/http 使用非常方便。只要组织好数据结构,就能轻松生成动态HTML页面。
以上就是Golang如何使用模板渲染动态页面的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号