-
Notifications
You must be signed in to change notification settings - Fork 23
4. View, Event and Flash Data
simple view struct are assigned in context. You can use some simple direct methods to operate view in context.
Directly render a template file:
ctx.Render("test",map[string]interface{...}))
The test means test.html
file in view directory(default is "view").
After rendered, the result bytes will be set to ctx.Body
.
If you need layout file support, use:
ctx.Layout("layout")
ctx.Render("test",map[string]interface{})
It will render layout as layout.layout
file after rendered test.
The layout file need content placeholder for template as {@Content}
.
Only render a file then get result:
str := ctx.Tpl("test",map[string]interface{}) // string
This method doesn't support layout file.
Add new template function:
ctx.Func("name",func(){...})
If you need view struct:
v := ctx.App().View() // *GoInk.View
GoInk.View
struct can run as single unit. Create a new view with directory:
v := GoInk.NewView("view_dir")
// change view dir dynamic
v.Dir = "other_view_dir"
View renders a file with whole file name:
bytes,err := v.Render("test.html",map[string]interface{})
So no matter template or layout file, pass filename to view.
Sometimes you need check the template file exist:
if v.Has("test.html"){
// go on something
}
Add new template function:
v.FuncMap["test"] = func(){}
Notice: View struct is created in *GoInk.App
.
The view in context is passed from *GoInk.App
.
So if you need change view settings, do it before app.Run()
.
And if you change something in context, it will affect global view.
Global view can be get from application either:
v := app.View()
Context supports simple event functions. You can define an event:
ctx.On("event_name",func(a int)int{
return a + 1
})
Then trigger it:
resultSlice := ctx.Do("event_name",1) // return []interface, now is [2]
Result slice need type assertion.
If run event in goroutine, you can:
go ctx.Do("event_name",1)
But can not get the result.
Notice: the input parameters are defined when ctx.On
.
If you pass less parameters when ctx.Do
, it prints error and returns nil.
If you pass more parameters, it uses the same number of ctx.On
function.
Extra parameters are ignored.
Context provides flash data to store temp data.
ctx.Flash("key",data)
data := ctx.Flash("key")
So you can set anything to flash data for context when doing handlers, such as session:
app.Use(func(ctx *GoInk.Context){
ctx.Flash("Session",NewFakeSession())
})
app.Get("/",func(ctx *GoInk.Context){
session := ctx.Flash("Session").(*FakeSession)
session.Start()
})
Flash data only servives in this lifecycle.