Golang

Go template模板

2019-05-21  本文已影响0人  xyz098

模板

text/template

关键点

核心

语法

pipelines

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.

# 渲染数据可以是go的所有类型
# 渲染数据本身
{{ . }}
# 自定义变量
{{ $var = . }}

# struct
# 大写字母开头属性Field 
{{ .Field }}
# 嵌套struct时的 属性Field1
{{ .Field.Field1 }}
# 变量为struct时的 属性Field
{{ $x = . }}
{{ $x.Field }}
# 方法
{{ .Method }}
# 嵌套struct的方法
{{ .Field.Method }}
# 嵌套struct的map中struct的方法
{{ .Field.Key.Method }}

# map
# 键名
{{ .key }}
# struct中map
{{ .Field.key }}
# 变量的struct中map
{{ $x = . }}
{{ $x.Field.key }}

# 函数
{{ funName . }}

操作

# 注释
{{/* comment */}}
{{- /* comment */ -}}

# 默认输出,效果 fmt.Print(pipeline)
{{ pipeline }}

# 流程控制
{{if pipeline}} T1 {{end}}
{{if pipeline}} T1 {{else}} T0 {{end}}
{{if pipeline}} T1 {{else if pipeline}} T0 {{end}}
{{with pipeline}} T1 {{end}}
{{with pipeline}} T1 {{else}} T0 {{end}}

# 循环
# array, slice, map, or channel
{{range pipeline}} T1 {{end}}
{{range pipeline}} T1 {{else}} T0 {{end}}

# 嵌套关联
{{template "name"}}
# 当前模板引入其他模板,并且传递数据
{{template "name" pipeline}}
# 等价声明和执行 {{define "name"}} T1 { {end}}  & {{template "name" pipeline}}
{{block "name" pipeline}} T1 {{end}} 

使用

func main() {
  stu := struct{Name string, ID int}{Name: "hello", ID: 11}
  
    // 创建模板对象, parse关联模板
    tmpl, err := template.New("test").Parse("{{.Name}} ID is {{ .ID }}")
    if err != nil {
        panic(err)
    }
    
    // 渲染stu为动态数据, 标准输出到终端
    err = tmpl.Execute(os.Stdout, stu)
    if err != nil {
        panic(err)
    }
}

// output
// hello ID is 1
上一篇下一篇

猜你喜欢

热点阅读