数据输出
直接输出字符串
func (c *MainController) Get() {
c.Ctx.WriteString("Hello World!")
}
模板数据输出
beego通过Controller 中的 c.Data 把数据输出到模板中
各种类型的数据渲染
基本
控制器数据赋值
func (c *MainController) Get() {
c.Data["Name"] = "xiaoming"
c.TplName = "hello.tpl"
}
模板渲染数据如下
the username is {{.Name}}
结构体
结构体结构
type A struct{
Name string
Age int
}
控制器数据赋值
this.Data["a"]=&A{Name:"astaxie",Age:25}
模板渲染数据如下:
the username is {{.a.Name}}
the age is {{.a.Age}}
map
控制器数据赋值
mp["name"]="astaxie"
mp["nickname"] = "haha"
this.Data["m"]=mp
模板渲染数据如下:
the username is {{.m.name}}
the username is {{.m.nickname}}
slice
控制器数据赋值
ss :=[]string{"a","b","c"}
this.Data["s"]=ss
模板渲染数据如下:
{{range $key, $val := .s}}
{{$key}}
{{$val}}
{{end}}
json | xml | jsonp
格式数据输出
通过把要输出的数据放到Data["json"] | Data["xml"] | Data["jsonp"]
中,然后调用ServeJSON()
进行渲染,就可以把数据进行JSON序列化输出。
调用 ServeJSON 之后,会设置 content-type
为 application/json | application/xml | application/javascript
,然后同时把数据进行 JSON | XML | JSON
序列化输出。
c.Data["json"] = 数据
c.ServeJSON()
c.Data["xml"] = 数据
c.ServeXML()
c.Data["jsonp"] = 数据
c.ServeJSONP()
json格式示例,其他格式一样
func (c *ArticleController) Show() {
//map类型的数据
mp["name"]="astaxie"
mp["nickname"] = "haha"
c.Data["json"] = map[string]interface{}{"code":0 ,"data": mp, "count": 10} //准备数据
c.ServeJSON() //渲染为json格式数据
return //返回json数据,供需要此数据的地方调用
//struct类型的数据
mystruct := { ... }
this.Data["json"] = &mystruct
this.ServeJSON()
return
}
响应
响应到模板 c.TplName
func (c *ArticleController) Show() {
c.Layout = "admin/layouts/layout.tpl"
c.TplName = "admin/article/add.tpl"
}
重定向
重定向到路由 c.Redirect
func (c *ArticleController) Show() {
c.Redirect("/", 302)
}
重定向到当前页面可以用重定向到路由方式实现
重定向到上一个页面的URL
func (c *ArticleController) Show() {
c.Ctx.Request.Referer()
}
重定向到当前页面URL
func (c *ArticleController) Show() {
c.Ctx.Request.RequestURI
}