商城首页欢迎来到中国正版软件门户

您的位置:首页 >Golang模板渲染技巧详解

Golang模板渲染技巧详解

  发布于2025-12-01 阅读(0)

扫一扫,手机访问

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

import ( "os" "text/template" )

func main() { const templateStr = "Hello, {{.Name}}! You are {{.Age}} years old.\n"

// 定义数据结构
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

import ( "html/template" "log" "net/http" )

func handler(w http.ResponseWriter, r *http.Request) { tmpl := <h1>Hello, {{.}}</h1> t, err := template.New("page").Parse(tmpl) if err != nil { log.Fatal(err) }

// 即使输入包含HTML,也会被转义
t.Execute(w, "<script>alert('hack')</script>")

}

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"}}{{end}}
{{define "content"}}

Main Content

{{end}} {{define "footer"}}{{end}}

执行特定块:

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

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

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注