背景:
本篇使用beego框架實驗了一下 golangMVC之view
view 就是展示層,beego中採用了 go temple 解析具體的字段 ,這樣可以將數據寫入到 control層| models層 控制,view層只做爲展示層即可。實現了數據 暫時分離。
實驗
1.先創建一個 control 的go文件
package controllers
import (
"WEB/models"
"github.com/astaxie/beego"
)
//ViewController is a Controller to handel struct of models
type ViewController struct {
beego.Controller
}
//Get is a function
func (c *ViewController) Get() {
var (
users []models.UserInfo
)
models.ReadUserInfo(&users)
c.Data["Users"] = users
c.TplName = "users.tpl"
}
我們創建一個新的control 文件 ,用於獲取所有的用戶信息,通過調用models層中的ReadUserInfo方法獲取所有用戶
同時將獲取的用戶 放入到 模版字段 Users中 ,然後解析模版使用的是 users.tpl
定義模版解析字段的時候 這個格式是固定的
c.Data["Users"] = users
c.TplName = "users.tpl"
爲什麼是這個樣子呢?
我們看control的定義
Data就是可以存儲任何數據的map ,TplName 就是 簡單的string類型
2.定義 view層
<html>
<title> view test</title>
<body>
{{ range .Users }}
{{ .Username }} {{.Password}}<br>
{{ end }}
</body>
</html>
我們通過一個range 循環去讀取了 users []models.UserInfo users數組中所有的數據
3.增加 route
在route.go中增加對應 control的路由即可
4.重新啓動程序
bee run
5.瀏覽器訪問
我們可以看到解析出來的字段