Go 模板的动作就是一些嵌入到模板里面的命令,这些命令在模板中需要放到两个
大括号里
{{
动作
}}
,之前我们已经用过一个
很重要的动作
:点(.),它代表了传递给模
板的数据。
条件动作
<html>
<head>
<title>模板文件</title>
<meta charset="utf-8"/>
</head>
<body>
<!-- 嵌入动作 -->
{{if .}}
你已经成年了!
{{else}}
你还未成年
{{end}}
</body>
</html>
func handler(w http.ResponseWriter, r *http.Request) {
//解析模板文件
t := template.Must(template.ParseFiles("hello.html"))
//声明一个变量
age := 16
//执行模板
t.Execute(w, age > 18)
}
在mian函数里调用,写法
http.HandleFunc("/testIf",testIf)
<body>
{{if .}}
{{end}}
{{if .}}
条件满足将显示我
{{else}}
else的内容
{{end}}
</body>
迭代动作
range 后面的点代表被遍历的元素;要显示的内容里面的点代表遍历
到的元素
<html>
<head>
<title>模板文件</title>
<meta charset="utf-8"/>
</head>
<body>
<!-- 嵌入动作 -->
{{range .}}
<a href="#">{{.}}</a>
{{else}}
没有遍历到任何内容
{{end}}
</body>
</html>
func handler(w http.ResponseWriter, r *http.Request) {
//解析模板文件
t := template.Must(template.ParseFiles("hello.html"))
//声明一个字符串切片
stars := []string{"马蓉", "李小璐", "白百何"}
//执行模板
t.Execute(w, stars)
}