contrib icon indicating copy to clipboard operation
contrib copied to clipboard

Use templates from go-bindata?

Open cytec opened this issue 9 years ago • 5 comments

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

cytec avatar Feb 07 '15 21:02 cytec

I'm interested to.

rogierlommers avatar Aug 02 '15 12:08 rogierlommers

I'm interested to.

aimuzov avatar Aug 02 '15 13:08 aimuzov

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)

cytec avatar Aug 02 '15 16:08 cytec

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

mzupan avatar Jan 16 '16 14:01 mzupan

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",
        })
    })
}

hryamzik avatar Mar 05 '16 19:03 hryamzik