mirror of https://github.com/gofiber/fiber.git
🔥 Add Global ViewLayout (#1384)
* Add Global Layout for view render * Add test case for Views Layout * Update ctx_test.gopull/1387/head
parent
c08568e247
commit
cb5f2f7eab
|
@ -0,0 +1 @@
|
|||
<h1>I'm main</h1>
|
5
app.go
5
app.go
|
@ -174,6 +174,11 @@ type Config struct {
|
|||
// Default: nil
|
||||
Views Views `json:"-"`
|
||||
|
||||
// Views Layout is the global layout for all template render until override on Render function.
|
||||
//
|
||||
// Default: ""
|
||||
ViewsLayout string `json:"views_layout"`
|
||||
|
||||
// The amount of time allowed to read the full request including body.
|
||||
// It is reset after the request handler has returned.
|
||||
// The connection's read deadline is reset when the connection opens.
|
||||
|
|
6
ctx.go
6
ctx.go
|
@ -888,6 +888,12 @@ func (c *Ctx) Render(name string, bind interface{}, layouts ...string) error {
|
|||
defer bytebufferpool.Put(buf)
|
||||
|
||||
if c.app.config.Views != nil {
|
||||
// Render template based on global layout if exists
|
||||
if len(layouts) == 0 && c.app.config.ViewsLayout != "" {
|
||||
layouts = []string{
|
||||
c.app.config.ViewsLayout,
|
||||
}
|
||||
}
|
||||
// Render template from Views
|
||||
if err := c.app.config.Views.Render(buf, name, bind, layouts...); err != nil {
|
||||
return err
|
||||
|
|
21
ctx_test.go
21
ctx_test.go
|
@ -1639,7 +1639,11 @@ type testTemplateEngine struct {
|
|||
}
|
||||
|
||||
func (t *testTemplateEngine) Render(w io.Writer, name string, bind interface{}, layout ...string) error {
|
||||
return t.templates.ExecuteTemplate(w, name, bind)
|
||||
if len(layout) == 0 {
|
||||
return t.templates.ExecuteTemplate(w, name, bind)
|
||||
}
|
||||
_ = t.templates.ExecuteTemplate(w, name, bind)
|
||||
return t.templates.ExecuteTemplate(w, layout[0], bind)
|
||||
}
|
||||
|
||||
func (t *testTemplateEngine) Load() error {
|
||||
|
@ -1662,6 +1666,21 @@ func Test_Ctx_Render_Engine(t *testing.T) {
|
|||
utils.AssertEqual(t, "<h1>Hello, World!</h1>", string(c.Response().Body()))
|
||||
}
|
||||
|
||||
// go test -run Test_Ctx_Render_Engine_With_View_Layout
|
||||
func Test_Ctx_Render_Engine_With_View_Layout(t *testing.T) {
|
||||
engine := &testTemplateEngine{}
|
||||
engine.Load()
|
||||
app := New(Config{ViewsLayout: "main.tmpl"})
|
||||
app.config.Views = engine
|
||||
c := app.AcquireCtx(&fasthttp.RequestCtx{})
|
||||
defer app.ReleaseCtx(c)
|
||||
err := c.Render("index.tmpl", Map{
|
||||
"Title": "Hello, World!",
|
||||
})
|
||||
utils.AssertEqual(t, nil, err)
|
||||
utils.AssertEqual(t, "<h1>Hello, World!</h1><h1>I'm main</h1>", string(c.Response().Body()))
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=Benchmark_Ctx_Render_Engine -benchmem -count=4
|
||||
func Benchmark_Ctx_Render_Engine(b *testing.B) {
|
||||
engine := &testTemplateEngine{}
|
||||
|
|
Loading…
Reference in New Issue