Skip to content

Instantly share code, notes, and snippets.

@lujiacn
Last active August 29, 2015 14:16
Show Gist options
  • Save lujiacn/2e1cfde959eca4821b3a to your computer and use it in GitHub Desktop.
Save lujiacn/2e1cfde959eca4821b3a to your computer and use it in GitHub Desktop.
From http://gorevel.cn/topic/14
1、使用刀符$访问全局变量,后面一种可以简化代码,省去了临时变量的定义
{{$user := .user}}
{{range .bookings}}
{{$user.Name}}
{{end}}
或(推荐)
{{range .bookings}}
{{$.user.Name}}
{{end}}
2、在循环中使用计数
{{range $index, $book := .books}}
{{$index}} {{$book}}
{{end}}
3、and or not,if else
{{if and false false}}<h1>It works!</h1>{{end}}
{{if or false false}}<h1>It works!</h1>{{end}}
{{if not false}}<h1>It works!</h1>{{end}}
{{if false}}<h1>It works!</h1>{{else if true}}oh yeah{{end}}
4、len 返回对象长度
{{len .bookings}}
5、urlquery转义
{{urlquery "http://golang.org"}}
6、巧用$.errors,服务端校验出错后,带回字段信息
{{with $field := field "category.Name" .}}
<input type="text" value="{{if $.errors}}{{$field.Flash}}{{else}}{{$field.Value}}{{end}}">
{{end}}
7、index,取回对象中的某个元素,支持array、map 、slice、string。
{{$book := index .bookings 0}}
{{$value := index .map “key”}}
8、比较
== {{eq 0 1}}
!= {{ne 0 1}}
< {{lt 0 1}}
<= {{le 0 1}}
> {{gt 0 1}}
>= {{ge 0 1}}
9、HTML 转义 ,比如将“<”改成“&lt”。
{{. | html}}
10、pad,生成指定长度空格 &nbsp;
{{pad "" 4}}
11、printf,格式化小数
{{printf "%.2f" 100.1234}}
12、输出原生HTML
{{raw .html}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment