這是一個建立於
的文章,其中的資訊可能已經有所發展或是發生改變。
我們知道,代碼裡面可以使用UrlFor或者模板裡面使用urlfor來根據自訂Controller和方法來產生url。這裡模板中使用的urlfor其實是UrlFor註冊的模板方法,二者功能完全相同,一個用於代碼中,另外一個用於模板中。
步驟如下:
- 自訂Controller,並且實現對應的方法Method
- 使用
beego.Router註冊路由,將自訂Controller執行個體和方法Method聯絡在一起
- 使用
UrlFor函數在代碼中或者urlfor在模板中產生url
上面的是我們經常會使用的方法,這裡再分享一個帶參數的UrlFor或者urlfor的用法。
package mainimport ( "fmt" "github.com/astaxie/beego")type UserController struct { beego.Controller}func (this UserController) List() {}func main() { userController := UserController{} //註冊路由 beego.Router("/user/list/:name/:age", &userController, "*:List") beego.Router("/user/list", &userController, "*:List") //建立url //{{urlfor "UserController.List" ":name" "astaxie" ":age" "25"}} url := userController.UrlFor("UserController.List", ":name", "astaxie", ":age", "25") //輸出 /user/list/astaxie/25 fmt.Println(url) //{{urlfor "UserController.List" "name" "astaxie" "age" "25"}} url = userController.UrlFor("UserController.List", "name", "astaxie", "age", "25") //輸出 /user/list?name=astaxie&age=25 fmt.Println(url) }
我們上面分別使用了路由參數的方式和表單參數的方式來分別建立了兩個url。對應的注釋中是它們在模板中的使用方法。
/*/user/list/astaxie/25*/{{urlfor "UserController.List" ":name" "astaxie" ":age" "25"}}/*/user/list?name=astaxie&age=25*/{{urlfor "UserController.List" "name" "astaxie" "age" "25"}}
需要注意的是,在模板中給方法提供的參數中間是用空格隔開的,另外注意路由參數和表單參數兩種方式下,路由的註冊方式和參數名稱的提供方式。帶冒號(:)的參數名是路由參數。另外參數的提供方式是依次以key-value方式提供的。