added a support of a "block" template feature from go1.6

fixed #567
This commit is contained in:
im7mortal 2016-04-03 00:17:26 +03:00
parent 4a6bc4aac4
commit 675af529c9
6 changed files with 92 additions and 0 deletions

View File

@ -0,0 +1,10 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
{{block "head" .}} {{end}}
</head>
<body>
{{block "body" .}} {{end}}
</body>
</html>

View File

@ -0,0 +1,19 @@
package main
import "github.com/gin-gonic/gin"
func main() {
router := gin.Default()
router.AddHTMLTemplate("/", "layouts/default.html", "views/blocks1.html")
router.AddHTMLTemplate("/blocks2/", "layouts/default.html", "views/blocks2.html")
router.GET("/", render)
router.GET("/blocks2/", render)
router.Run(":8080")
}
func render(c *gin.Context) {
c.HTML(200, c.Request.URL.Path, gin.H{})
}

View File

@ -0,0 +1,7 @@
{{define "head"}}
<title>Blocks 1</title>
{{end}}
{{define "body"}}
<a href="/blocks2/">Go to blocks 2</a>
{{end}}

View File

@ -0,0 +1,7 @@
{{define "head"}}
<title>Blocks 2</title>
{{end}}
{{define "body"}}
<a href="/">Go to blocks 1</a>
{{end}}

16
gin.go
View File

@ -147,6 +147,22 @@ func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
engine.HTMLRender = render.HTMLProduction{Template: templ}
}
// AddHTMLTemplate allow to use "block" template feature from go1.6
func (engine *Engine) AddHTMLTemplate(name string, paths... string) {
var templateStorage render.TemplateStorage
t, ok := engine.HTMLRender.(render.TemplateStorage)
if ok {
templateStorage = t
} else {
if len(engine.trees) > 0 {
debugPrintWARNINGSetHTMLTemplate()
}
templateStorage = render.TemplateStorage{make(map[string]*template.Template)}
}
templateStorage.Storage[name] = template.Must(template.ParseFiles(paths...))
engine.HTMLRender = templateStorage
}
// Adds handlers for NoRoute. It return a 404 code by default.
func (engine *Engine) NoRoute(handlers ...HandlerFunc) {
engine.noRoute = handlers

View File

@ -0,0 +1,33 @@
// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package render
import (
"html/template"
"net/http"
)
type TemplateStorage struct {
Storage map[string]*template.Template
}
func (t TemplateStorage) Instance(name string, data interface{}) Render {
return HTMLwithBlock{
Template: t.Storage[name],
Name: name,
Data: data,
}
}
type HTMLwithBlock struct {
Template *template.Template
Name string
Data interface{}
}
func (r HTMLwithBlock) Render(w http.ResponseWriter) error {
writeContentType(w, htmlContentType)
return r.Template.Execute(w, r.Data)
}