文章目录 (?) [+]
测试用的变量和方法
type struct Blog {
Title string
}
map[string]interface{}
type FuncMap map[string]interface{}
func add(x, y int) int变量
{{/* . 代表传入模板的 struct 或 map 变量 */}}
<p>{{. Title}}</p>
{{/* 定义变量的两种方法 */}}
{{$name := "test"}}
{{$name := .Title}}
<p>{{$name}}</p>
{{/* 创建封闭作用域*/}}
{{with "hello"}}
{{/* 此处的 . 即为 hello */}}
<p>{{.}}</p>
{{else}}
{{/* 此处的 . 为原来的上下文 */}}
<p>{{.}}</p>
{{end}}
{{/* 对于数组,切片,map 使用索引,相当于 array[2][3][4] */}}
<p>{{index array 2 3 4}</p>管道
{{/* 调用 FuncMap 中的函数 */}}
<p>{{12.345 | printf "%.2f"}}</p>判断
{{/* bool 类型判断 */}}
{{if .conditon1}}
<p>1</p>
{{else if .conditon2}}
<p>2</p>
{{else}}
<p>3</p>
{{end}}
{{/* 与 */}}
{{if and .conditon1 .conditon2}}
<p>&&</p>
{{end}}
{{/* 或 */}}
{{if or .conditon1 .conditon2}}
<p>||</p>
{{end}}
{{/* 非 */}}
{{if not .conditon}}
<p>!</p>
{{end}}
{{/* 等于 */}}
{{if eq .conditon1 .conditon2}}
<p>==</p>
{{end}}
{{/* 不等于 */}}
{{if ne .conditon1 .conditon2}}
<p>!=</p>
{{end}}
{{/* 小于 */}}
{{if lt .conditon1 .conditon2}}
<p>less than</p>
{{end}}
{{/* 小于等于 */}}
{{if le .conditon1 .conditon2}}
<p>less than equal</p>
{{end}}
{{/* 大于 */}}
{{if gt .conditon1 .conditon2}}
<p>greater than</p>
{{end}}
{{/* 大于等于 */}}
{{if ge .conditon1 .conditon2}}
<p>greater than or equal to</p>
{{end}}遍历
{{/* 遍历 map 或 slice */}}
{{range $i, $v := .slice}}
<p>index:{{$i}} value: {{$v}}</p>
{{end}}
{{range .slice}}
<p>value: {{.field}}</p>
<p>访问外部变量{{$.Title}}</p>
{{end}}函数
{{/* 调用模板方法 */}}
<p>{{add 1 2}}</p>嵌套
layout
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{.Title}}</title>
</head>
<body>
{{/* 为了子模板获取父模板的变量应在其后加 . */}}
{{template "article" .}}
</body>
</html>template
{{define "article"}}
<article>
<header>{{.Header}}</header>
<section>{{.Section}}</section>
<footer>{{.Footer}}</footer>
</article>
{{end}}