Golang下的html/template模块使用

  • 2019 年 10 月 4 日
  • 筆記

撸了今年阿里、头条和美团的面试,我有一个重要发现…….>>>

关于template模板,Golang语言提供了两个包text/templatehtml/template,前者主要用来处理文本文件的变量渲染,而后者主要用于对html之类的网页文件进行渲染。由于最近在使用gin框架编写REST API,顺便学习template的使用,再此记录一下。

html/template常用的对象和方法

template模板的使用主要是在对Template结构体的相关方法进行操作。我们首先得初始化一个Template对象。

type Template struct {      Tree *parse.Tree  }    # 初始化一个template对象  ## Must函数会在Parse返回err不为nil时,调用panic,不需要初始化后再调用Parse方法去检测  func Must(t *Template,err error) *Template  ## New函数用来创建一个指定的HTML模板  func New(name string) *Template  ## ParseFiles函数用来从一个指定的文件中创建并解析模板  func ParseFiles(filenames ...string) (*Template, error)  ## ParseGlob函数从指定的匹配文件中创建并解析模板,必须得至少匹配一个文件  func ParseGlob(pattern string) (*Template, error)    # Template结构体对象常用的几个方法    ## 使用New()函数创建的模板需要指定模板内容  func (t *Template) Parse(text string) (*Template, error)    ## Delims()方法用来指定分隔符来分割字符串,随后会使用Parse, ParseFiles, or ParseGlob方法进行模板内容解析  func (t *Template) Delims(left, right string) *Template    ## Execute()方法用来把一个模板解析到指定的数据对象data中,并且写入到输出wr中。如果有任何错误,就like停止,但如果是并行操作的话,有一些数据已经被写入了。因此,使用该方法一定要注意并发安全性  func (t *Template) Execute(wr io.Writer, data interface{}) error    ## 同上  func (t *Template) ExecuteTemplate(wr io.Writer, name string, data interface{}) error

示例程序

# 模板文件  $ $ cat app.tpl  <!DOCTYPE html>  <html>  <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">      <title>layout</title>    </head>    <body>      <h3>userslist:</h3>      <p>userlist:</p>{{ .}}      <p>users:</p>      {{range $i,$e := .}}          {{$i}}:{{$e}}      {{end}}      {{range .}}          {{ .}}      {{end}}    </body>  </html>    # 示例程序  $ cat golanghtml.go  package main  import (      "html/template"      "os"  )    func main() {      /*      1.声明一个Template对象并解析模板文本      func New(name string) *Template      func (t *Template) Parse(text string) (*Template, error)        2.从html文件解析模板      func ParseFiles(filenames ...string) (*Template, error)        3.模板生成器的包装      template.Must(*template.Template, error )会在Parse返回err不为nil时,调用panic。      func Must(t *Template, err error) *Template        t := template.Must(template.New("name").Parse("html"))      */          t, _ :=template.ParseFiles("app.tpl")      //t,_ := template.ParseGlob("*.tpl")          t.Execute(os.Stdout, []string{"bgbiao","biaoge"})    }    $ go run golanghtml.go  <!DOCTYPE html>  <html>  <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">      <title>layout</title>    </head>    <body>      <h3>userslist:</h3>      <p>userlist:</p>[bgbiao biaoge]      <p>users:</p>            0:bgbiao            1:biaoge              bgbiao            biaoge      </body>  </html>

可以看到,html文本成功的将我们定义的[]string{"bgbiao","biaoge"}进行渲染并输出了。