Add support for c.HTML with asset file from go-bindata

This commit is contained in:
Jianbo Feng 2016-08-05 22:47:43 +08:00
parent f931d1ea80
commit e2f1a0e9f9
2 changed files with 55 additions and 0 deletions

View File

@ -483,6 +483,23 @@ func main() {
router.Run(":8080") router.Run(":8080")
} }
``` ```
Or if you need package template into execute file by [go-bindata](https://github.com/jteeuwen/go-bindata)
Just run `go-bindata path/to/tempalte` before to generate `bindata.go` first.
Then use `LoadHTMLBinData()` as below:
```go
func main() {
router := gin.Default()
router.LoadHTMLBinData(AssetNames(), MustAsset)
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
})
})
router.Run(":8080")
}
```
templates/index.tmpl templates/index.tmpl
```html ```html
<html> <html>

38
gin.go
View File

@ -9,6 +9,7 @@ import (
"net" "net"
"net/http" "net/http"
"os" "os"
"path/filepath"
"sync" "sync"
"github.com/gin-gonic/gin/render" "github.com/gin-gonic/gin/render"
@ -140,6 +141,43 @@ func (engine *Engine) LoadHTMLFiles(files ...string) {
} }
} }
//Load HTML Template from BinData, which generate by go-bindata from https://github.com/jteeuwen/go-bindata
//Usage:
// 1. Install go-bindata by `go get https://github.com/jteeuwen/go-bindata/...`
// 2. Run `go-bindata path/to/template`, then you can find a file named as `bindata.go`
// 3. Check this file, it must defined two method `AssetNames()` and `MustAssets()`
// 4. Use return value of AssetNames() as params files, and MustAssets itself (NOT return value of it) as params fileAssetFunc
// 5. If needed, filter invalid template asset names return by AssetNames() before use.
func (engine *Engine) LoadHTMLBinData(files []string, fileAssetFunc func(string)([]byte)) {
if IsDebugging() {
engine.HTMLRender = render.HTMLDebug{Files: files}
} else {
var templ *template.Template
for _, filename := range files {
content := fileAssetFunc(filename)
name := filepath.Base(filename)
var tmpl *template.Template
if templ == nil {
templ = template.New(name)
}
if name == templ.Name() {
tmpl = templ
} else {
tmpl = templ.New(name)
}
_, err := tmpl.Parse(string(content))
if err != nil {
panic("template " + filename + " parse failed: " + err.Error())
}
}
engine.SetHTMLTemplate(templ)
}
}
func (engine *Engine) SetHTMLTemplate(templ *template.Template) { func (engine *Engine) SetHTMLTemplate(templ *template.Template) {
if len(engine.trees) > 0 { if len(engine.trees) > 0 {
debugPrintWARNINGSetHTMLTemplate() debugPrintWARNINGSetHTMLTemplate()