文章目录
我们知道,代码里面可以使用UrlFor
或者模板里面使用urlfor
来根据自定义Controller
和方法来生成url
。这里模板中使用的urlfor
其实是UrlFor
注册的模板方法,二者功能完全相同,一个用于代码中,另外一个用于模板中。
步骤如下:
- 自定义
Controller
,并且实现对应的方法Method
- 使用
beego.Router
注册路由,将自定义Controller
实例和方法Method
联系在一起
- 使用
UrlFor
函数在代码中或者urlfor
在模板中生成url
上面的是我们经常会使用的方法,这里再分享一个带参数的UrlFor
或者urlfor
的用法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| 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 := userController.UrlFor("UserController.List", ":name", "astaxie", ":age", "25") fmt.Println(url)
url = userController.UrlFor("UserController.List", "name", "astaxie", "age", "25") fmt.Println(url) beego.UrlFor("UserController.List") }
|
我们上面分别使用了路由参数的方式和表单参数的方式来分别创建了两个url
。对应的注释中是它们在模板中的使用方法。
1 2 3 4 5 6 7 8 9 10 11 12 13
|
{{urlfor "UserController.List" ":name" "astaxie" ":age" "25"}}
{{urlfor "UserController.List" "name" "astaxie" "age" "25"}}
{{urlfor "UserController.List"}}
|
需要注意的是,在模板中给方法提供的参数中间是用空格隔开的,另外注意路由参数和表单参数两种方式下,路由的注册方式和参数名称的提供方式。带冒号(:)
的参数名是路由参数。另外参数的提供方式是依次以key-value
方式提供的。
本文引自这里