模板函数

创建一个名字为name的模板

  1. func New(name string) *Template

解析模板字符串

  1. func (t *Template) Parse(text string) (*Template, error)

解析文件

  1. func (t *Template) ParseFiles(filenames ...string) (*Template, error)

执行模板,将结果写入wr

  1. func (t *Template) Execute(wr io.Writer, data interface{}) error

注册函数给模板,注册之后模板就可以通过名字调用外部函数

  1. func (t *Template) Funcs(funcMap FuncMap) *Template
  2. type FuncMap map[string]interface{}

对象解析

{{}}来包含需要在渲染时被替换的字段,{{.}}表示当前的对象
如果要访问当前对象的字段通过{{.FieldName}},但是需要注意一点:这个字段必须是导出的(字段首字母必须是大写的),否则在渲染的时候就会报错

  1. import (
  2. "html/template"
  3. "log"
  4. "os"
  5. )
  6. type User struct {
  7. Name string
  8. Age int
  9. }
  10. func main(){
  11. tmpl,err := template.New("Demo").Parse("My name is {{.Name}}\n I am {{.Age}} year old")
  12. if err!=nil {
  13. log.Fatal("Parse error",err);
  14. }
  15. err = tmpl.Execute(os.Stdout,User{
  16. Name :"bx",
  17. Age :23,
  18. })
  19. if err!=nil {
  20. log.Fatal("execute error",err);
  21. }
  22. }

{{range.}}{{end}}

  1. import (
  2. "html/template"
  3. "os"
  4. )
  5. func main(){
  6. slice := []string{"test1","test2"}
  7. tmpl,_:= template.New("slice").Parse("{{range.}}{{.}}\n{{end}}")
  8. tmpl.Execute(os.Stdout,slice)
  9. }

pipeline/管道

pipeline 翻译过来可以称为管道或者流水线, pipeline运算的作用是将多个函数调用或者值串起来,从左往右执行,左边执行的结果会传递给右边,形成一个任务流水。
pipeline运算符:| (竖线)
语法格式:

  1. command1 | command2 | command3 ...

command可以是一个值,也可以是一个函数。
例子1:

  1. {{"<h1>www.tizi365.com</h1>" | html}}

这里意思就是将第一个字符串值传递给html函数。

eg:

  1. func main(){
  2. const temStr = `{{. | printf "%s"}}`
  3. t := template.Must(template.New("demo").Parse(temStr))
  4. t.Execute(os.Stdout, "hello world")
  5. }

内置函数

函数名 函数调用格式 对应关系运算 说明
eq eq arg1 arg2 arg1 == arg2 arg1等于arg2则返回true
ne ne arg1 arg2 arg1 != arg2 arg1不等于arg2则返回true
lt lt arg1 arg2 arg1 < arg2 arg1小于arg2则返回true
le le arg1 arg2 arg1 <= arg2 arg1小于等于arg2则返回true
gt gt arg1 arg2 arg1 > arg2 arg1大于arg2则返回true
ge ge arg1 arg2 arg1 >= arg2 arg1大于等于arg2则返回true

逻辑运算函数

函数名 函数调用格式 对应逻辑运算 说明
and and 表达式1 表达式2 表达式1 && 表达式2 表达式1和表达式2都为真的时候返回true
or or 表达式1 表达式2 表达式1 || 表达式2 表达式1和表达式2其中一个为真的时候返回true
not not 表达式 !表达式 表达式为false则返回true, 反之返回false

函数调用

  1. import (
  2. "html/template"
  3. "os"
  4. )
  5. func foo(str string)(result string){
  6. return "hello "+str
  7. }
  8. func main(){
  9. t, _:= template.New("demo").Funcs(template.FuncMap{"foo":foo}).Parse("{{.|foo}}")
  10. t.Execute(os.Stdout,"test")
  11. }

参考

https://www.tizi365.com/archives/90.html
https://github.com/griffin702/ginana