登录
推荐 文章 Go 技术 课程 下载 专题 AI
首页 >  Golang >  Go教程

Go语言模板渲染详解:text/template使用教程

时间:2025-12-25 22:08:51 340浏览 收藏

大家好,我们又见面了啊~本文《Go语言模板渲染教程:text/template使用详解》的内容中将会涉及到等等。如果你正在学习Golang相关知识,欢迎关注我,以后会给大家带来更多Golang相关文章,希望我们能一起进步!下面就开始本文的正式内容~

Golang的text/template用于动态生成文本,支持数据绑定、条件循环控制、自定义函数及模板嵌套。通过{{.}}引用数据,if/range实现逻辑判断与遍历,FuncMap注册函数如upper,define/template实现模块化复用,适用于配置、日志等文本生成场景。

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

在Golang中使用 text/template 渲染模板非常实用,尤其适用于生成文本输出,如日志、配置文件、邮件内容等。它通过将数据结构与模板结合,动态生成所需文本。

1. 基本用法:定义模板并渲染数据

使用 text/template 包的第一步是创建一个模板字符串,然后将数据注入其中。

示例:

package main

import ( "os" "text/template" )

type User struct { Name string Age int }

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

tmpl := template.Must(template.New("user").Parse(templateStr))

user := User{Name: "Alice", Age: 25}
tmpl.Execute(os.Stdout, user)

}

输出:

Hello, Alice! You are 25 years old.

{{.Name}}{{.Age}} 是模板中的占位符,. 表示当前数据上下文。

2. 控制结构:条件判断与循环

模板支持 ifrange 等控制逻辑,便于处理复杂数据。

示例:使用 if 判断和 range 遍历切片

const templateStr = `
{{if .Active}}
Status: Active
{{else}}
Status: Inactive
{{end}}

Friends: {{range .Friends}}- {{.}} {{end}} `

type Person struct { Active bool Friends []string }

person := Person{ Active: true, Friends: []string{"Bob", "Charlie", "Dana"}, }

tmpl := template.Must(template.New("status").Parse(templateStr)) tmpl.Execute(os.Stdout, person)

输出:

Status: Active

Friends:

  • Bob
  • Charlie
  • Dana

3. 设置函数模板:自定义模板函数

你可以注册自定义函数,供模板内部调用。

示例:添加一个转大写的函数

funcMap := template.FuncMap{
    "upper": strings.ToUpper,
}

tmpl := template.New("withFunc").Funcs(funcMap) tmpl, _ = tmpl.Parse("Hello, {{.Name | upper}}!\n")

user := User{Name: "bob"} tmpl.Execute(os.Stdout, user)

输出:Hello, BOB!

| 是管道操作符,将前面的值传给后面的函数。

4. 模板嵌套与组合

可以定义多个模板片段,并通过 template 动作嵌入。

const mainTmpl = `
{{define "Greeting"}}
Hello, {{.Name}}
{{end}}

{{define "Info"}} You are {{.Age}} years old. {{end}}

{{template "Greeting" .}} {{template "Info" .}} `

tmpl := template.Must(template.New("combined").Parse(mainTmpl)) tmpl.Execute(os.Stdout, User{Name: "Eve", Age: 30})

这样可以实现模板复用,适合生成结构化文本。

基本上就这些。只要掌握数据绑定、控制结构和函数扩展,就能灵活使用 text/template 生成各种文本内容。

理论要掌握,实操不能落!以上关于《Go语言模板渲染详解:text/template使用教程》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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