beego中帶參數的UrlFor和urlfor的用法講解

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

我們知道,代碼裡面可以使用UrlFor或者模板裡面使用urlfor來根據自訂Controller和方法來產生url。這裡模板中使用的urlfor其實是UrlFor註冊的模板方法,二者功能完全相同,一個用於代碼中,另外一個用於模板中。

步驟如下:

  1. 自訂Controller,並且實現對應的方法Method
  2. 使用beego.Router註冊路由,將自訂Controller執行個體和方法Method聯絡在一起
  3. 使用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方式提供的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.