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"}進行渲染並輸出了。