iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 6
0
Modern Web

BeeGo系列 第 6

Controller and View(1)

今天來小試一下,新增一個關於頁面。

一般在 MVC 架構裡要新增一個頁面,得新增一個 Controller 跟 View 。在 Django 是新增一個 Class-based view 或是一個 Function-based view,然後再新增樣板 HTML 檔案。

在 BeeGo 裡,我們可以用 bee 這個工具來快速的產生所需的 Controller。

bee generate controller about

在執行這個指令以後,controllers 目錄下會多出一個 about.go ,我們打開看看 bee 幫我們產生了什麼。

首先我們可以看到他繼承了 beego.Controller (好好好,我知道 go 裏面其實沒有繼承,但 composite 在某種程度來說,算是一種繼承關係)

// AboutController operations for About
type AboutController struct {
    beego.Controller
}

然後在 URLMapping() 裡描述了這個 Controller 處理了哪些 HTTP Method。

// URLMapping ...
func (c *AboutController) URLMapping() {
    c.Mapping("Post", c.Post)
    c.Mapping("GetOne", c.GetOne)
    c.Mapping("GetAll", c.GetAll)
    c.Mapping("Put", c.Put)
    c.Mapping("Delete", c.Delete)
}

再往下看,可以看到 Post(), GetOne(), ... 等等函式。

因為我們只顯示一個簡單的頁面,所以我們把不必要的都拿掉,並且做一些調整

// URLMapping ...
func (c *AboutController) URLMapping() {
    c.Mapping("Get", c.Get)
}

func (c *AboutController) Get() {
    // View (Template) 裡要用到的變數
    c.Data["Name"] = "John Doe"
    // 指定 View (Template) 檔名
    c.TplName = "about.tpl"
}

接著在 views 目錄下,新增 View (Template),命名為 about.tpl

<!DOCTYPE html>

<html>
<head>
  <title>About</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>

<body>
  <h1>About</h1>
  <p>Hello, {{.Name}}</p>                                                                                                                                                                                                                                        
</body>
</html>

最後再調整 Router (routers/router.go)

func init() {
    beego.Router("/", &controllers.MainController{})
    // 新增下面這行
    beego.Router("/about", &controllers.AboutController{})
}

執行下面指令,再用瀏覽器去瀏覽 http://localhost:8080/about/ 就可以看到剛剛新增的關於頁面了。

bee run

上一篇
ORM(2)
下一篇
Controller and View(2)
系列文
BeeGo30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言