你确定不学?Go标准库之 text/template

简介: 你确定不学?Go标准库之 text/template

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


初级应用

text/template库的使用

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

package main

import (
  "os"
  "text/template"
)

func main() {
  // 模板字符串
  const tpl = `Hi, {{.Name}}! Welcome to {{.Website}}.`

  // 准备模板数据
  data := struct {
    Name    string
    Website string
  }{
    Name:    "Go语言中文网",
    Website: "https://studygolang.com",
  }

  // 创建模板对象并解析模板字符串
  tmpl, err := template.New("test").Parse(tpl)
  if err != nil {
    panic(err)
  }

  // 使用数据渲染模板,并将结果输出到标准输出
  err = tmpl.Execute(os.Stdout, data)
  if err != nil {
    panic(err)
  }
}

上面的代码中,我们首先定义了一个模板字符串tpl,然后创建一个模板对象并解析这个字符串,最后将准备好的数据传递给模板,模板就会按照预定的格式把数据渲染进去。

html/template库的使用

html/template库实际上是text/template库的超集,它比text/template库多了一些针对HTML格式的功能。尤其是,html/template库能够对插入到HTML页面的内容进行适当的转义,以防止一些常见的安全问题,如XSS攻击。下面的例子展示了如何使用html/template库来生成一个HTML页面。

package main

import (
  "html/template"
  "os"
)

type Person struct {
  Name string
  Age  int
}

func main() {
  const tpl = `
  <!DOCTYPE html>
  <html>
    <head>
      <title>Hello</title>
    </head>
    <body>
      <h1>Hello, {{.Name}}</h1>
      <p>You are {{.Age}} years old.</p>
    </body>
  </html>`

  data := Person{
    Name: "Go语言中文网",
    Age:  7,
  }

  tmpl, err := template.New("test").Parse(tpl)
  if err != nil {
    panic(err)
  }

  err = tmpl.Execute(os.Stdout, data)
  if err != nil {
    panic(err)
  }
}

启动程序,你会在控制台看到生成的HTML代码。

这两个标准库使得在Golang中使用模板变得非常容易。在Go web开发中,进行HTML渲染时,我们通常会选用html/template库。而在需要处理一般的文本格式时,我们选择text/template库。

进阶应用

除了基本的模板渲染之外,html/templatetext/template 库还提供了一些更高级的模板操作。这需要让我们理解模板的一个重要概念:管道(pipeline)。管道可以让我们在模板中进行更为复杂的逻辑处理,例如条件判断、循环以及自定义函数。

  1. 条件判断 使用{{if}}...{{end}}{{else}}语句
 const tpl = `Hi, {{if .Married}}Mr{{else}}Miss{{end}}, {{.Name}}`
 tmpl, err := template.New("test").Parse(tpl)
 if err != nil {
     log.Fatal(err)
 }

 data := struct {
     Name    string
     Married bool
 }{
     Name:    "Go语言中文网",
     Married: false,
 }

 err = tmpl.Execute(os.Stdout, data)
 if err != nil {
     log.Fatal(err)
 }
  1. 循环 使用{{range}}...{{end}}语句
 const tpl = `{{range .}} Hi, {{.Name}}.{{end}}`
 tmpl, err := template.New("test").Parse(tpl)
 if err != nil {
     log.Fatal(err)
 }

 data := [] struct {
     Name    string
 }{
     {"Go语言"},
     {"C语言"},
     {"Python"},
 }

 err = tmpl.Execute(os.Stdout, data)
 if err != nil {
     log.Fatal(err)
 }
  1. 自定义函数
    我们还可以定义自定义的函数,并在模板中使用它们。这是通过Funcs方法来实现的:
 func ToUpper(str string) string {
     return strings.ToUpper(str)
 }

 const tpl = `Hi, {{.Name | toUpper}}.`
 tmpl, err := template.New("test").Funcs(template.FuncMap{
     "toUpper": ToUpper,
 }).Parse(tpl)
 if err != nil {
     log.Fatal(err)
 }

 data := struct {
     Name string
 }{
     Name: "Go语言中文网",
 }

 err = tmpl.Execute(os.Stdout, data)
 if err != nil {
     log.Fatal(err)
 }
相关文章
|
25天前
|
Shell Go API
Go语言grequests库并发请求的实战案例
Go语言grequests库并发请求的实战案例
|
3天前
|
Linux 编译器 Go
cgo--在Go中链接外部C库
cgo--在Go中链接外部C库
|
3天前
|
Rust Go C语言
Python通过C动态链接库调用Go语言函数
Python通过C动态链接库调用Go语言函数
|
2月前
|
JSON 中间件 Go
go语言后端开发学习(四) —— 在go项目中使用Zap日志库
本文详细介绍了如何在Go项目中集成并配置Zap日志库。首先通过`go get -u go.uber.org/zap`命令安装Zap,接着展示了`Logger`与`Sugared Logger`两种日志记录器的基本用法。随后深入探讨了Zap的高级配置,包括如何将日志输出至文件、调整时间格式、记录调用者信息以及日志分割等。最后,文章演示了如何在gin框架中集成Zap,通过自定义中间件实现了日志记录和异常恢复功能。通过这些步骤,读者可以掌握Zap在实际项目中的应用与定制方法
go语言后端开发学习(四) —— 在go项目中使用Zap日志库
|
2月前
|
存储 JSON 前端开发
一文搞懂 Go 1.21 的日志标准库 - slog
一文搞懂 Go 1.21 的日志标准库 - slog
65 2
|
2月前
|
Prometheus Cloud Native Go
Go 1.22 标准库 slices 新增函数和一些旧函数增加新特性
Go 1.22 标准库 slices 新增函数和一些旧函数增加新特性
|
2月前
|
XML Go 数据库
|
6天前
|
存储 Go 容器
深入探究Go语言中的数据结构
深入探究Go语言中的数据结构
23 3
|
16天前
|
Go
Go 语言循环语句
在不少实际问题中有许多具有规律性的重复操作,因此在程序中就需要重复执行某些语句。
25 1
|
5天前
|
Go
GO语言时间转换
GO语言时间转换
16 0