首页 > 后端开发 > Golang > 正文

如何在Golang中使用template渲染模板

P粉602998670
发布: 2025-10-22 08:53:01
原创
486人浏览过
使用Golang模板需选择text/template或html/template,后者防XSS;通过Parse解析字符串模板,Execute渲染数据,支持嵌套字段、if/range控制结构;HTML模板自动转义恶意内容;可加载文件模板并用ParseGlob批量解析,ExecuteTemplate执行指定块。

如何在golang中使用template渲染模板

在Golang中使用template渲染模板非常直接,主要通过标准库中的 text/templatehtml/template 实现。前者用于普通文本模板,后者专为HTML设计,具备自动转义功能,防止XSS攻击。

1. 基本用法:定义和渲染模板

你可以通过字符串或文件定义模板,然后将数据注入其中进行渲染。

示例代码:

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.

2. 使用嵌套字段和条件判断

模板支持访问结构体的嵌套字段、使用if条件、range循环等控制结构。

示例:

AiPPT模板广场
AiPPT模板广场

AiPPT模板广场-PPT模板-word文档模板-excel表格模板

AiPPT模板广场 147
查看详情 AiPPT模板广场
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"},
    },
}
登录后复制

3. 使用 HTML 模板并防止 XSS

如果你生成的是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>

页面不会执行脚本,确保安全。

4. 加载模板文件

实际项目中模板通常存放在文件中。可以使用 template.ParseFilestemplate.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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号