go template简明教程

背景

go template 有两个库:

  • text/template: 标准模版库
  • html/template: for html template 的库,提供更安全的解析方式

两个库用法基本一样

代码示例

package main  
  
import (  
    "os"  
    "text/template")  
  
type Pet struct {  
    Name   string  
    Sex    string  
    Intact bool  
    Age    string  
    Breed  string  
}  
  
func main() {  
    dogs := []Pet{  
       {  
          Name:   "Jujube",  
          Sex:    "Female",  
          Intact: false,  
          Age:    "10 months",  
          Breed:  "German Shepherd/Pitbull",  
       },  
       {  
          Name:   "Zephyr",  
          Sex:    "Male",  
          Intact: true,  
          Age:    "13 years, 3 months",  
          Breed:  "German Shepherd/Border Collie",  
       },  
    }  
    parseString(dogs)  
    // parseFile(dogs)  
}  
  
func parseString(dogs []Pet) {  
    tmplStr := `Number of dogs: {{ . | len }}  
Number of dogs: {{ len . -}}  
{{ range . }}  
---  
Name:  {{ .Name }}  
  
Sex:   {{ .Sex }} ({{ if .Intact }}intact{{ else }}fixed{{ end }})  
  
Age:   {{ .Age }}  
  
Breed: {{ .Breed }}  
{{ end }}`  
  
    tmpl, err := template.New("mytest").Parse(tmplStr)  
    if err != nil {  
       panic(err)  
    }  
    err = tmpl.Execute(os.Stdout, dogs)  
    if err != nil {  
       panic(err)  
    }  
}  
  
func parseFile(dogs []Pet) {  
    var tmplFile = "pets.tmpl"  
    tmpl, err := template.New(tmplFile).ParseFiles(tmplFile)  
    if err != nil {  
       panic(err)  
    }  
    err = tmpl.Execute(os.Stdout, dogs)  
    if err != nil {  
       panic(err)  
    }  
} // end main

基本概念

Action

值替换或者控制流称为 action,用{{}}表示:

值替换:{{ .Value }}
控制流: {{ if .Value }} true branch {{ else }} false branch {{ end }}

值替换语法和类型

用dot 逐级引用,数据类型可以是struct 的成员或者 map key

空格和换行

action 前后都可以通过-trim掉空白字符,空白字符包括空格和换行符.
注意对于 {{ range .Values }} 这样的“控制行“也会打印出一个空行

Pipeline

值替换的结果就是一个 pipeline,原文解释”A pipeline is a possibly chained sequence of "commands". A command is a simple value (argument) or a function or method call, possibly with multiple arguments“。官方文档中pipeline 出现的示例。

{{pipeline}}

{{if pipeline}} T1 {{end}}

Arguments

就当做函数参数即可,不必过于纠结。一个示例:

.Method [Argument...]

Variables

Action中可定义变量,用于后续的 action。

{{with $x := "output" | printf "%q"}}{{$x}}{{end}}
    A with action that creates and uses a variable.

Function

可以在 action 中调用调用函数

有两种调用方法
{{ len .Values }}   按照函数名,参数的方式调用

{{ .Values | len }} 使用|来调用

函数的几种类型

  • 内置函数:列表见文档,直接调用
  • 变量的成员函数:用 call 命令调用
  • 自定义函数:通过 Funcs函数调用: template.New(tmplFile).Funcs(funcMap).ParseFiles(tmplFile)

Reference

一篇比较好的指引文档

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容