使用Golang的html/template可安全渲染动态数据,通过定义模板文件、准备可导出字段的数据结构,并调用Execute方法注入数据,自动转义防止XSS。

使用Golang的
html/template
Execute
在项目中创建一个HTML文件,比如
index.html
templates/
<!DOCTYPE html>
<html>
<head><title>用户信息</title></head>
<body>
<h1>欢迎,{{.Name}}!</h1>
<p>你今年 {{.Age}} 岁。</p>
<ul>
{{range .Hobbies}}
<li>{{.}}</li>
{{end}}
</ul>
</body>
</html>
这里
{{.Name}}{{.Age}}{{range .Hobbies}}在Go代码中,使用
template.ParseFiles
Execute
立即学习“go语言免费学习笔记(深入)”;
package main
import (
"html/template"
"log"
"net/http"
)
type User struct {
Name string
Age int
Hobbies []string
}
func handler(w http.ResponseWriter, r *http.Request) {
// 定义数据
user := User{
Name: "张三",
Age: 25,
Hobbies: []string{"读书", "游泳", "编程"},
}
// 解析模板文件
tmpl, err := template.ParseFiles("templates/index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// 执行模板,将数据写入响应
err = tmpl.Execute(w, user)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func main() {
http.HandleFunc("/", handler)
log.Println("服务器启动在 http://localhost:8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}
启动服务后访问
http://localhost:8080
支持嵌套结构、map、条件判断等。例如模板中使用
{{if .IsAdult}}...{{end}}
{{if ge .Age 18}}
<p>你是成年人。</p>
{{else}}
<p>你还未成年。</p>
{{end}}
也可以使用
template.ParseGlob
{{template "header"}}基本上就这些。只要数据结构和模板字段匹配,
html/template
以上就是如何用Golang的html/template包向网页动态渲染数据的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号