golang tempalte使用

这篇文章发表于 2021年12月22日,星期三,14:39阅读 0

经常在脚本编写中需要使用到模版tempalte,用来静态生成文件、代码,总结如下。

template中define使用

在使用编写template时可以使用{{define}}{{end}}来命名模版,在模版引入时直接使用命名即可,如下: header.tpl

{{define header}} header demo {{end}}

article.tpl

{{define article}} {{template header .}} {{end}}

然后在golang中使用**template.ParseFiles(filenames ...string)**解析所有的模版:

t, err := template.ParseFiles("/article.tpl", "header.tpl") if err != nil { panic(err) } var buf bytes.Buffer // 这里的article指定解析的入口模版,当在解析和输出时如果发生错误,将停止,但这是可能buf已经被写入了部分数据,需要注意。 err = t.ExecuteTemplate(&buf, "article", data) if err != nil { panic(err) } return buf.String()

条件判断

  1. if else
struct Person { Age int Sex string } tom := Person{ Age: 20, Sex: "男", } // xxx t.Execute(&buf, tom)
{{if gt .Age 20}} rather than 20 {{else if eq .Age 20}} equal 20 {{else}} less than 20 {{end}}

上面的代码中表示大于、等于,在条件判断中需要使用end作为结尾的标识符。

  1. 内置函数 eq 等于
{{if eq val1 val2}}{{end}} ne 不等于 {{if ne val1 val2}}{{end}} gt 大于 {{if gt val1 val2}}{{end}}

lt 大于 {{if lt val1 val2}}{{end}}

ge 大于等于
{{if ge val1 val2}}{{end}}

le 大于等于 {{if le val1 val2}}{{end}}

and 与
{{if and .cond1 .cond2}}{{end}}
or 或
{{if or .cond1 .cond2}}{{end}}
not 非
{{if not .cond1 }}{{end}}


年龄大于20的男性
```tpl
{{if and (gt .Age 20) (eq .Sex "男")}}
{{end}

年龄小于20,或者不是男性

{{if or (lt .Age 20) (ne .Sex "男")}} {{end}

template.FuncMap

模版中提供的内置函数无法满足业务场景,要添加自定义函数,提供了template.FuncMapy用来注册自定义方法

func lowerCase(str string) string { return xxx; } func1 := template.FuncMap{"lowerCase": lowerCase} t.Funcs(func1)

上面注册了一个将名称转为小写的方法lowerCase,在模版中使用如下

{{lowerCase .Name}}

有多个参数的话直接在后面追家即可

模版读取

经常会将模版写在单独的文件中,就需要读取文件,可以使用path/filepath来获取绝对路径

file, err := filepath.Abs(tplPath) if err != nil { panic(err) }