0

I am using the echo framework in Go to create a web app. I have a directory called templates inside which I have two directories layouts and users. The directory tree is as follows:

layouts
|--------default.tmpl
|--------footer.tmpl
|--------header.tmpl
|--------sidebar.tmpl

users
|--------index.tmpl

The code for header, footer, and sidebar are similar with:

{{define "header"}}
<!-- some html here -->
{{ end }} 
....

default.tmpl is as 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, I parse the files using

t := &Template{}
t.templates = template.Must(template.ParseGlob("views/layouts/*"))
t.templates = template.Must(template.ParseGlob("views/user/*"))

And try to render it

func User(c echo.Context) error {
    return c.Render(http.StatusOK, "index", nil)
}

But I only get an internal server error. I don't know how to debug the templates either. The code works if the users\index.tmpl does not contain other template tags inside it. But when I try to include the main template in it, the error returns. What am I doing wrong here?

rahules
  • 807
  • 3
  • 12
  • 33

1 Answers1

2

Managed to solve this. This page https://elithrar.github.io/article/approximating-html-template-inheritance/ helped. Basically, I had to change the code with which I parsed the 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)
}

for _, layout := range layouts {
    files := append(layouts, tpls)
    t.templates = template.Must(template.ParseFiles(files...))
}
rahules
  • 807
  • 3
  • 12
  • 33