golang常用库之-标准库text/template

文章目录

golang常用库之-标准库text/template

背景

在许多编程场景中,我们经常需要把数据按照某种格式进行输出,比如生成HTML页面,或者生成配置文件。这时,我们就需要模板引擎的帮助。幸运的是,Go语言在标准库中就提供了两个强大的模板引擎:text/template和html/template。

什么是text/template

text/template是Go语言标准库中的一个强大工具,用于生成文本输出。它允许你定义模板,然后将数据填充到模板中,非常适合生成报告、配置文件、HTML等。

text/template库的使用

text/template库用于生成任何基于文本的格式。它使用双大括号{{和}}来定义模板的动态部分。让我们通过一个简单的例子来看一下它的使用方法。

  1. 简单的字符串插值
go 复制代码
package main

import (
    "os"
    "text/template"
)

func main() {
    // 定义模板
    tmpl := template.Must(template.New("test").Parse("你好,{{.Name}}!今天是{{.Date}}。\n"))
    
    // 准备数据
    data := struct {
        Name string
        Date string
    }{
        Name: "张三",
        Date: "2025年5月1日",
    }
    
    // 执行模板并输出到标准输出
    err := tmpl.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }
}

go 复制代码
package main

import (
    "os"
    "text/template"
)

func main() {
    // 显式创建template.Template对象
    var tmpl *template.Template
    tmpl = template.New("hello")
    
    // 解析模板内容
    tmpl, err := tmpl.Parse("你好,{{.Name}}!今天是{{.Date}}。\n")
    if err != nil {
        panic(err)
    }
    
    // 准备数据
    data := struct {
        Name string
        Date string
    }{
        Name: "张三",
        Date: "2025年5月2日",
    }
    
    // 执行模板
    err = tmpl.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }
}
  1. 使用循环(range)
go 复制代码
package main

import (
    "os"
    "text/template"
)

func main() {
    // 定义模板
    const templateText = `
我的购物清单:
{{range .Items}}
- {{.}}
{{end}}

总计: {{.Count}}项
`
    tmpl := template.Must(template.New("list").Parse(templateText))
    
    // 准备数据
    data := struct {
        Items []string
        Count int
    }{
        Items: []string{"苹果", "香蕉", "橙子", "牛奶"},
        Count: 4,
    }
    
    // 执行模板
    err := tmpl.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }
}
  1. 条件语句(if-else)
go 复制代码
package main

import (
    "os"
    "text/template"
)

func main() {
    // 定义模板
    const templateText = `
{{if .Success}}
✅ 操作成功: {{.Message}}
{{else}}
❌ 操作失败: {{.Message}}
{{end}}

状态码: {{.Code}}
`
    tmpl := template.Must(template.New("status").Parse(templateText))
    
    // 准备数据 - 成功案例
    success := struct {
        Success bool
        Message string
        Code    int
    }{
        Success: true,
        Message: "数据已保存",
        Code:    200,
    }
    
    // 执行模板
    tmpl.Execute(os.Stdout, success)
    
    // 失败案例
    failure := struct {
        Success bool
        Message string
        Code    int
    }{
        Success: false,
        Message: "服务器错误",
        Code:    500,
    }
    
    tmpl.Execute(os.Stdout, failure)
}
  1. 自定义函数
bash 复制代码
package main

import (
    "os"
    "strings"
    "text/template"
    "time"
)

func main() {
    // 创建模板并添加自定义函数
    funcMap := template.FuncMap{
        "upper":     strings.ToUpper,
        "formatDate": func(t time.Time) string {
            return t.Format("2006年01月02日")
        },
    }
    
    tmpl := template.New("funcs")
    tmpl.Funcs(funcMap)
    
    // 解析模板
    tmpl, err := tmpl.Parse(`
用户: {{.Name | upper}}
注册时间: {{.RegisterDate | formatDate}}
`)
    if err != nil {
        panic(err)
    }
    
    // 准备数据
    data := struct {
        Name         string
        RegisterDate time.Time
    }{
        Name:         "李四",
        RegisterDate: time.Date(2024, 3, 15, 0, 0, 0, 0, time.UTC),
    }
    
    // 执行模板
    err = tmpl.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }
}
相关推荐
三体世界29 分钟前
TCP传输控制层协议深入理解
linux·服务器·开发语言·网络·c++·网络协议·tcp/ip
kangkang-32 分钟前
PC端基于SpringBoot架构控制无人机(二):MavLink协议
java·spring boot·后端·无人机
随心点儿1 小时前
使用python 将多个docx文件合并为一个word
开发语言·python·多个word合并为一个
不学无术の码农1 小时前
《Effective Python》第十三章 测试与调试——使用 Mock 测试具有复杂依赖的代码
开发语言·python
tomcsdn311 小时前
SMTPman,smtp的端口号是多少全面解析配置
服务器·开发语言·php·smtp·邮件营销·域名邮箱·邮件服务器
EnigmaCoder1 小时前
Java多线程:核心技术与实战指南
java·开发语言
麦兜*1 小时前
Spring Boot秒级冷启动方案:阿里云FC落地实战(含成本对比)
java·spring boot·后端·spring·spring cloud·系统架构·maven
喷火龙8号2 小时前
MSC中的Model层:数据模型与数据访问层设计
后端·架构
5ycode2 小时前
dify项目结构说明与win11本地部署
后端·开源
LaoZhangAI2 小时前
GPT-image-1 API如何传多图:开发者完全指南
前端·后端