当前位置: 首页 > ai >正文

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

文章目录

  • golang常用库之-标准库text/template
    • 背景
    • 什么是text/template
    • text/template库的使用

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

背景

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

什么是text/template

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

text/template库的使用

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

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

package mainimport ("os""text/template"
)func main() {// 显式创建template.Template对象var tmpl *template.Templatetmpl = template.New("hello")// 解析模板内容tmpl, err := tmpl.Parse("你好,{{.Name}}!今天是{{.Date}}。\n")if err != nil {panic(err)}// 准备数据data := struct {Name stringDate string}{Name: "张三",Date: "2025年5月2日",}// 执行模板err = tmpl.Execute(os.Stdout, data)if err != nil {panic(err)}
}
  1. 使用循环(range)
package mainimport ("os""text/template"
)func main() {// 定义模板const templateText = `
我的购物清单:
{{range .Items}}
- {{.}}
{{end}}总计: {{.Count}}项
`tmpl := template.Must(template.New("list").Parse(templateText))// 准备数据data := struct {Items []stringCount int}{Items: []string{"苹果", "香蕉", "橙子", "牛奶"},Count: 4,}// 执行模板err := tmpl.Execute(os.Stdout, data)if err != nil {panic(err)}
}
  1. 条件语句(if-else)
package mainimport ("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 boolMessage stringCode    int}{Success: true,Message: "数据已保存",Code:    200,}// 执行模板tmpl.Execute(os.Stdout, success)// 失败案例failure := struct {Success boolMessage stringCode    int}{Success: false,Message: "服务器错误",Code:    500,}tmpl.Execute(os.Stdout, failure)
}
  1. 自定义函数
package mainimport ("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         stringRegisterDate 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)}
}
http://www.xdnf.cn/news/3413.html

相关文章:

  • C++负载均衡远程调用学习之消息队列与线程池
  • 【前端知识】Vue3状态组件Pinia详细介绍
  • 同城跑腿小程序帮取帮送接单抢单预约取件智能派单同城配送全开源运营版源码优创
  • Python实例题:Python获取小说数据并分析
  • 计算方法实验四 解线性方程组的间接方法
  • 使用 n8n 创建一个定时获取“RSS新闻“的工作流
  • (35)VTK C++开发示例 ---将图片映射到平面2
  • 期刊、出版社、索引数据库
  • 从0搭建Transformer
  • 逻辑回归的多分类实战:以鸢尾花数据集为例
  • STL之vector容器
  • MySQL 索引不生效的情况
  • 【Linux】Linux基础概念
  • 树状数组 + 线段树
  • Java学习手册:Spring Security 安全框架
  • 多模态人工智能研究:视觉语言模型的过去、现在与未来
  • 51单片机驱动 矩阵键盘
  • SPOJ 11576 TRIP2 - A Famous King’s Trip 【Tarjan+欧拉回路】
  • Python清空Word段落样式的方法
  • PINNs案例——多介质分区温度场
  • c++环境和vscode常用的一些有用插件
  • 菲索旋转齿轮法:首次地面光速测量的科学魔术
  • Spring Boot 集成 Elasticsearch 的详细步骤
  • Arduino按键开关编程详解
  • Ubuntu 安装 MySQL8
  • Mybatis学习笔记
  • pytest——参数化
  • btrace1.0使用方法
  • AE模板 300个故障干扰损坏字幕条标题动画视频转场预设
  • mysql--索引