Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Nested html templates. #156

Open
heatxsink opened this issue Apr 22, 2020 · 4 comments
Open

Nested html templates. #156

heatxsink opened this issue Apr 22, 2020 · 4 comments

Comments

@heatxsink
Copy link

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

@constraintAutomaton
Copy link

I also have this problem, have you found a solution

@heatxsink
Copy link
Author

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

@constraintAutomaton
Copy link

constraintAutomaton commented Jul 22, 2020

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

@precisionpete
Copy link

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

}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants