golang : MVC之view

背景:
本篇使用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.瀏覽器訪問
我們可以看到解析出來的字段
![在這裏插入圖片描述](https://img-blog.csdnimg.cn/20191028105315739.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RleHRkZW1vMTIz,size_16,color_FFFFFF,t_70

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章