douyoupingji7238 2015-12-08 22:09
浏览 173
已采纳

Beego会话不会自动将数据传递到模板

Upon getting session information of type map[string]interface{} with this.GetSession("session_key"), I did have to explicitly set the context and type assert the session like this in order to explicitly pass the data to the template.

// Get the session
profile := this.GetSession("profile")

// Have to add data to the template's context
this.Data["nickname"] = profile.(map[string]interface{})["nickname"].(string)
this.Data["picture"] = profile.(map[string]interface{})["picture"].(string)

// Render template
this.TplNames = "user.html"

The session data (type map[string]interface{}) looks like this:

{"nickname": "joe", "picture": "urltotheimg"}

However, according to the Beego's session doc, it looks like the session is passed implicitly without any need of type assertions or context passing (the template has immediate access to session values i.e. {{.nickname}} and {{.picture}})

This is the controller setting the session before redirecting to /user

// Inherit beego's base controller
type MyController struct {
    beego.Controller
}

func (this *MyController) Get() {

    // code for getting token here

    // Getting the User information
    client := conf.Client(oauth2.NoContext, token)
    resp, err := client.Get("https://" + domain + "/userinfo")
    if err != nil {
        this.Redirect("/error", 500)
        return
    }

    // Reading the body for user's information
    raw, err := ioutil.ReadAll(resp.Body)
    defer resp.Body.Close()
    if err != nil {
        this.Redirect("/error", 500)
        return
    }

    // Unmarshalling the JSON of the Profile
    var profile map[string]interface{}
    if err := json.Unmarshal(raw, &profile); err != nil {
        this.Redirect("/error", 500)
        return
    }

    // Saving the information to the session.
    this.SetSession("profile", profile)

    // redirect to /user
    this.Redirect("/user", 301)
}

This is the controller of "/user"

type UserController struct {
    beego.Controller
}

func (this *UserController) Get() {
    // get the saved session
    profile := this.GetSession("profile")

    // without setting the template data here, the session data won't be
    // available in user.html
    this.Data["nickname"] = profile.(map[string]interface{})["nickname"].(string)
    this.Data["picture"] = profile.(map[string]interface{})["picture"].(string)
    this.TplNames = "user.html"
}

Only this then I can map the template to the data like this:

<img src="{{ .picture }}">
<p>Hello, {{ .nickname }}</p>

I'm quite sure it's necessary to set the template data. I'm just not sure why the above doc didn't do that.

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • duanjue2560 2015-12-12 06:52
    关注

    I just tried running the Beego quickstart project and ran it successfully.

    Make sure you have both the beego and bee installed. After creating a new project with bee new projectname make sure you edit the projectname/conf/app.conf file and add the sessionon = true:

    appname = quickstart
    httpport = 8080
    runmode = dev
    sessionon = true
    

    I created a redirect controller like:

    type RedirectController struct {
        beego.Controller
    }
    
    func (c *RedirectController) Get() {
        profile := make(map[string]interface{})
        profile["nickname"] = "User's Nickname"
        profile["picture"] = "/path/to/img.jpg"
    
        c.SetSession("profile", profile)
        c.Redirect("/", 301)
    }
    

    The main controller:

    type MainController struct {
        beego.Controller
    }
    
    func (c *MainController) Get() {
        profile := c.GetSession("profile")
    
        c.Data["nickname"] = profile.(map[string]interface{})["nickname"]
        c.Data["picture"] = profile.(map[string]interface{})["picture"]
        c.TplNames = "index.tpl"
    }
    

    My index.tpl file:

    <p>Nickname: {{.nickname}}</p>
    <p>Picture: {{.picture}}</p>
    

    And the router:

    func init() {
        beego.Router("/", &controllers.MainController{})
        beego.Router("/redirect", &controllers.RedirectController{})
    }
    

    I would also recommend you to use a structure to store the profile values like:

    // Define struct.
    type Profile struct{
        Nickname string
        Picture  string
    }
    
    // Save it for template rendering.
    this.Data["profile"] = &Profile{Nickname:"astaxie", Picture:"img.jpg"}
    
    // And render it like this:
    Nickname: {{.profile.Nickname}}
    Picture:  {{.profile.Picture}}
    

    Make sure to read this to understand how template rendering is done. I hope this is what you were asking for, if not, please edit your question and add more helpful information and I will edit this answer.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值