登录
首页 >  Golang >  Go教程

Golang模板渲染教程:如何使用template包

时间:2025-11-19 09:43:13 265浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《Golang模板渲染教程:如何使用template包》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

使用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)
}

}

输出结果:

Hello, Alice! You are 30 years old.

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

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

示例:

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>")

}

func main() { http.HandleFunc("/", handler) http.ListenAndServe(":8080", nil) }

浏览器中实际输出为:

Hello,

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

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"}}{{end}}
{{define "content"}}<h1>Main Content</h1>{{end}}
{{define "footer"}}{{end}}

执行特定块:

t.ExecuteTemplate(os.Stdout, "content", nil)

基本上就这些。掌握解析、数据绑定、控制结构和文件加载,就能灵活使用Go模板。关键是根据场景选择 text/template 还是 html/template,避免安全问题。

今天关于《Golang模板渲染教程:如何使用template包》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>