go.rice icon indicating copy to clipboard operation
go.rice copied to clipboard

Nested html templates.

Open heatxsink opened this issue 5 years ago • 4 comments
trafficstars

Cannot find a good example of nesting html templates with go.rice. Has anyone tried / successfully done this?

heatxsink avatar Apr 22 '20 17:04 heatxsink

I also have this problem, have you found a solution

constraintAutomaton avatar Jul 18 '20 22:07 constraintAutomaton

This is what I ended up doing ... if anyone has a better method please lmk ... https://gist.github.com/heatxsink/67e1d098f63425efd350e4625c0b13dc

heatxsink avatar Jul 20 '20 03:07 heatxsink

I ended up doing this, I could also "walk in the folder" recursively to populate my files []string. I also shouldn't panic without sending data to the user ...

viewsBox := rice.MustFindBox("../views") //my templates are in this folder
files := []string{"bar.html",
	"components/foo1.html",
	"components/foo2.html",
	"components/foo/bar1.html",
	"components/foo/bar2.html",
	"components/foo/bar2.html"}
tmpl := template.New("foo")
for _, el := range files {
	fileContent, err := viewsBox.String(el)
	if err != nil {
		panic(err)
	}
	tmpl, err = tmpl.Parse(fileContent)
	if err != nil {
		panic(err)
	}
}

constraintAutomaton avatar Jul 22 '20 19:07 constraintAutomaton

I figured this much out...

func renderTemplate(w http.ResponseWriter, templateName string, data map[string]interface{}) {

	tBox, err := rice.FindBox("../templates")
	if err != nil {
		fmt.Println(err)
	}

	tLayout, err := tBox.String("layout.gohtml")
	if err != nil {
		fmt.Println(err)
	}

	tPage, err := tBox.String(templateName)
	if err != nil {
		fmt.Println(err)
	}

	tmpl := template.New("")
	tmpl, err = tmpl.Parse(tLayout)
	if err != nil {
		fmt.Println(err)
	}

	tmpl, err = tmpl.Parse(tPage)
	if err != nil {
		fmt.Println(err)
	}

	err = tmpl.ExecuteTemplate(w, "layout", data)
	if err != nil {
		fmt.Println(err)
	}

}

precisionpete avatar Feb 08 '21 14:02 precisionpete