go - Rendering template in golang -
i using echo framework in go create web app. have directory called templates
inside have 2 directories layouts
, users
. directory tree follows:
layouts |--------default.tmpl |--------footer.tmpl |--------header.tmpl |--------sidebar.tmpl users |--------index.tmpl
the code header, footer, , sidebar similar with:
{{define "header"}} <!-- html here --> {{ end }} ....
default.tmpl
follows:
{{ define "default" }} {{ template "header" }} {{ template "sidebar" }} <div class="content-wrapper"> <div class="container-fluid"> <div class="row"> <div class="col-md-12"> <h2 class="page-title">dashboard</h2> {{ template "content" .}} </div> </div> </div> </div> {{ template "footer" }} {{ end }}
and users\index.tmpl
{{define "index"}} {{template "default"}} {{end}} {{define "content"}} <p>hello world</p> {{end}}
now, parse files using
t := &template{} t.templates = template.must(template.parseglob("views/layouts/*")) t.templates = template.must(template.parseglob("views/user/*"))
and try render
func user(c echo.context) error { return c.render(http.statusok, "index", nil) }
but internal server error. don't know how debug templates either. code works if users\index.tmpl
not contain other template tags inside it. when try include main template in it, error returns. doing wrong here?
managed solve this. page https://elithrar.github.io/article/approximating-html-template-inheritance/ helped. basically, had change code parsed templates to:
tpls, err := filepath.glob("views/user/*") if err != nil { log.fatal(err) } layouts, err := filepath.glob("views/layouts/*") if err != nil { log.fatal(err) } _, layout := range layouts { files := append(layouts, tpls) t.templates = template.must(template.parsefiles(files...)) }
Comments
Post a Comment