《The way to go》——模板动作 action 练习

1、action.go

package main

import (
	"net/http"
	"html/template"
)

//User 结构体
type User struct{
	ID int
	Username string
	Password string
	Email string
}


func testIf(w http.ResponseWriter, req *http.Request){
	//解析模板文件
	t:=template.Must(template.ParseFiles("if.html"))
	age := 17
	//执行
	t.Execute(w, age<18)
}

func testRange(w http.ResponseWriter, req *http.Request){
	users:=[]model.User{
		{ID:1,Username:"jason",Password:"123",Email:"jason@heng.com"},
		{ID:2,Username:"matt",Password:"456",Email:"matt@ha.com"},
		{ID:3,Username:"lee",Password:"789",Email:"lee@hei.com"},
	}

	//解析模板文件
	t:=template.Must(template.ParseFiles("range.html"))
	//执行
	t.Execute(w, users)
}

func testWith(w http.ResponseWriter, req *http.Request){
	//解析模板文件
	t:=template.Must(template.ParseFiles("with.html"))
	//执行
	t.Execute(w, "狸猫")
}

func testTemplate(w http.ResponseWriter, req *http.Request){
	//解析模板文件
	t:=template.Must(template.ParseFiles("template1.html","template2.html"))
	//执行
	t.Execute(w, "我能在两个文件中显示吗?")
}

func main(){
	http.HandleFunc("/testif", testIf)
	http.HandleFunc("/testrange", testRange)
	http.HandleFunc("/testwith", testWith)
	http.HandleFunc("/testtemplate", testTemplate)
	http.ListenAndServe(":8080",nil)
}

2、if.html

<html>
	<head>
		<meta charset="UTF-8"/>
	</head>
	<body>
		{{if .}}
		我要显示出来
		{{end}}
		<hr />
		{{if .}}
		如果传过来的是true将显示此内容
		{{else}}
		else中的内容被显示
		{{end}}
	</body>
</html>

3、with.html

<html>
	<head>
		<meta charset="UTF-8"/>
	</head>
	<body>
		{{with "太子"}}
		<div> 替换后数据:{{.}} </div>
		{{end}}

		<hr />
		{{with ""}}
		<div> 替换后数据:{{.}} </div>
		{{else}}
		<div> 传入的数据:{{.}} </div>
		{{end}}
	</body>
</html>

4、range.html

<html>
	<head>
		<meta charset="UTF-8"/>
	</head>
	<body>
		{{range .}}
			遍历到的元素是:<a href="#"> {{.Username}} </a><br/>
		{{else}}
			没有遍历到任何元素
		{{end}}
	</body>
</html>

5、template1.html

<html>
	<head>
		<meta charset="UTF-8"/>
	</head>
	<body>
		<div> 后台传过来的数据是:{{.}}</div>
		<div> 包含template2.html里面的内容 </div>
		{{template "template2.html"}}
		<hr/>
		{{template "template2.html" .}}
	</body>
</html>

6、template2.html

<html>
	<head>
		<meta charset="UTF-8"/>
	</head>
	<body>
		<div> template2.html里面传入的数据时:{{.}} </div>
	</body>
</html>
posted @ 2020-07-07 09:49  飞吧小鸡  阅读(134)  评论(0)    收藏  举报