mirror of
https://github.com/gin-gonic/gin.git
synced 2025-10-15 13:02:14 +08:00
Add support for c.HTML with asset file from go-bindata
This commit is contained in:
parent
f931d1ea80
commit
e2f1a0e9f9
17
README.md
17
README.md
@ -483,6 +483,23 @@ func main() {
|
||||
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
|
||||
```html
|
||||
<html>
|
||||
|
38
gin.go
38
gin.go
@ -9,6 +9,7 @@ import (
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
|
||||
"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) {
|
||||
if len(engine.trees) > 0 {
|
||||
debugPrintWARNINGSetHTMLTemplate()
|
||||
|
Loading…
x
Reference in New Issue
Block a user