Go语言通过html/template实现安全的HTML模板渲染,防止XSS攻击。首先定义模板内容或从文件加载,使用template.New或ParseFiles创建并解析模板,然后传入数据结构(如struct或map)执行渲染,输出到响应流或标准输出;支持条件判断(if-else)和循环(range)等逻辑控制;结合net/http包可在Web服务中动态返回渲染页面,适用于构建简单动态站点。

在Go语言中,实现基本的模板渲染主要依赖标准库中的 text/template 和 html/template 包。如果你需要生成HTML内容并确保输出安全,推荐使用 html/template;如果只是普通文本,可以使用 text/template。
html/template 是Go中最常用的模板包,特别适合Web开发,它会自动对数据进行HTML转义,防止XSS攻击。
基本步骤如下:
package main
import (
"html/template"
"log"
"os"
)
func main() {
// 定义模板内容
const tpl = `
<h1>Hello, {{.Name}}!</h1>
<p>You are {{.Age}} years old.</p>
`
// 创建模板并解析内容
t, err := template.New("example").Parse(tpl)
if err != nil {
log.Fatal(err)
}
// 定义数据
data := struct {
Name string
Age int
}{
Name: "Alice",
Age: 30,
}
// 执行模板,输出到标准输出
err = t.Execute(os.Stdout, data)
if err != nil {
log.Fatal(err)
}
}
运行后输出:
立即学习“go语言免费学习笔记(深入)”;
<h1>Hello, Alice!</h1> <p>You are 30 years old.</p>
实际项目中,模板通常保存在文件中。假设你有一个模板文件 index.html:
<!DOCTYPE html>
<html>
<head><title>User Profile</title></head>
<body>
<h2>Welcome, {{.Username}}</h2>
<p>Email: {{.Email}}</p>
</body>
</html>
Go代码读取并渲染:
t, err := template.ParseFiles("index.html")
if err != nil {
log.Fatal(err)
}
data := map[string]string{
"Username": "Bob",
"Email": "bob@example.com",
}
t.Execute(os.Stdout, data)
模板支持逻辑控制,如 if 判断和 range 遍历。
{{if .IsAdmin}}
<p>You have admin privileges.</p>
{{else}}
<p>You are a regular user.</p>
{{end}}
<ul>
{{range .Hobbies}}
<li>{{.}}</li>
{{end}}
</ul>
对应的数据结构:
data := struct {
IsAdmin bool
Hobbies []string
}{
IsAdmin: true,
Hobbies: []string{"Reading", "Coding", "Gaming"},
}
结合 net/http,可以在HTTP处理器中渲染模板返回给浏览器。
package main
import (
"net/http"
"html/template"
)
func handler(w http.ResponseWriter, r *http.Request) {
t, _ := template.ParseFiles("index.html")
data := map[string]string{"Username": "Charlie"}
t.Execute(w, data)
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
访问 http://localhost:8080 即可看到渲染后的页面。
基本上就这些。Go的模板系统简洁实用,配合结构体或map能快速完成数据填充,适合构建静态页面或简单动态站点。关键是理解上下文传递和语法格式,避免拼写错误导致解析失败。
以上就是Golang如何实现基本的模板渲染的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号