我们知道,代码里面可以使用UrlFor或者模板里面使用urlfor来根据自定义Controller和方法来生成url。这里模板中使用的urlfor其实是UrlFor注册的模板方法,二者功能完全相同,一个用于代码中,另外一个用于模板中。
步骤如下:
- 自定义Controller,并且实现对应的方法Method
- 使用beego.Router注册路由,将自定义Controller实例和方法Method联系在一起
- 使用UrlFor函数在代码中或者urlfor在模板中生成url
上面的是我们经常会使用的方法,这里再分享一个带参数的UrlFor或者urlfor的用法。
package main
import (
"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方式提供的。
作者:fatigue
https://blog.csdn.net/fatigue/article/details/42408391