gin-gonic / contrib

Collection of middlewares created by the community
https://gin-gonic.github.io/gin/
MIT License
2.04k stars 276 forks source link

Use templates from go-bindata? #23

Open cytec opened 9 years ago

cytec commented 9 years ago

Is there any way to use templates from go-bindatas BinaryFileSystem instead of loading them from disk?

rogierlommers commented 9 years ago

I'm interested to.

aimuzov commented 9 years ago

I'm interested to.

cytec commented 9 years ago

i've got it working this way:

//load templates from the asset that go-bindata provides
func loadTemplates(list ...string) *template.Template {

    for _, x := range list {
        templateString, err := Asset("assets/templates/" + x)
        if err != nil {
            log.Fatal(err)
        }

        // get file contents as string
        _, err = templates.New(x).Parse(string(templateString))
        if err != nil {
            log.Fatal(err)
        }
    }

    return templates
}

tmpl := loadTemplates("_script.tmpl", "_header.tmpl", "calendar.tmpl", "addSeries.tmpl", "history.tmpl", "shows.tmpl", "show.tmpl", "settings.tmpl", "presets.tmpl")
router.SetHTMLTemplate(tmpl)
mzupan commented 8 years ago

@cytec sorry new to Go but where is templates inited to deal with the return

hryamzik commented 8 years ago
func loadTemplates(list ...string) multitemplate.Render {
    r := multitemplate.New()

    for _, x := range list {
        templateString, err := Asset("templates/" + x)
        if err != nil {
            log.Fatal(err)
        }

        tmplMessage, err := template.New(x).Parse(string(templateString))
        if err != nil {
            log.Fatal(err)
        }

        r.Add(x, tmplMessage)
    }

    return r
}

func main() {
    router := gin.Default()
    router.HTMLRender = loadTemplates("index.tmpl","_script.tmpl", "_header.tmpl")
    router.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "title": "Main website",
        })
    })
}