🔥 Add Global ViewLayout (#1384)

* Add Global Layout for view render

* Add test case for Views Layout

* Update ctx_test.go
pull/1387/head
Sujit Baniya 2021-06-14 14:55:49 +05:45 committed by GitHub
parent c08568e247
commit cb5f2f7eab
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 32 additions and 1 deletions

1
.github/testdata/main.tmpl vendored Normal file
View File

@ -0,0 +1 @@
<h1>I'm main</h1>

5
app.go
View File

@ -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
View File

@ -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

View File

@ -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{}