golang: MVC 之 view

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/textdemo123/article/details/102777180

Background:
Benpian use beego framework of the experiment a bit golangMVC View
View is the presentation layer, beego adopted a go temple resolve specific fields, so you can write data to the control layer | models layer control, view only layer to the presentation layer It can be. We realized the data temporarily separated.
Experiment
1. First create a control file of 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"
}

We create a new control file to retrieve all user information, access to all users by calling ReadUserInfo method models layer
simultaneous users will get put into the template field Users, and then parse the template using users.tpl

Defined template fields when parsing this format is fixed

c.Data["Users"] = users
c.TplName = "users.tpl"

Why is it like this?
We look at the definition of control of
Here Insert Picture Description
Data that can store any map data, TplName is a simple string type
2. Define the view layer

<html>
    <title> view test</title>
    <body>
        {{ range .Users }}
        {{ .Username }} {{.Password}}<br>
        {{ end }}

    </body>
</html>

We cycle to read a range of users [] models.UserInfo users of all array data
3. The route increases
to increase the control corresponding to the route to the route.go
Here Insert Picture Description
4. Restart procedure
Bee RUN
Here Insert Picture Description
5. The browser accesses
our It can be seen parsing out the field
! [Insert Picture description here] (https://img-blog.csdnimg.cn/20191028105315739.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RleHRkZW1vMTIz,size_16,color_FFFFFF,t_70

Guess you like

Origin blog.csdn.net/textdemo123/article/details/102777180