Razmooo
Razmooo

Reputation: 506

Gin gonic templates overwriting partial templates

I am using gin gonic and it's features. One if them being html template rendering. So in spirit of DRY I wanted to create a base.html template with all common html tags etc. with a slot for different page bodies.

In essence, this is the base.html

{{define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

{{ template "main" . }}

</body>
</html>
{{end}}

Then I created a "child" template called home.html:

{{template "base" .}}

{{define "main"}}
    <div class="container mt-5">
        Hello
    </div>
{{end}}

I followed this wonderful guide on this page and it worked like a charm.

The problem

But when I tried adding another page with different body in subpage.html eg:

{{template "base" .}}

{{define "main"}}
<div class="container">
    <div>
        <h2>This page is still in progress</h2>
    </div>
</div>
{{end}}

the last template that is picked by gins LoadHTMLFiles or LoadHTMLGlob, is then displayed on every page. In this case this is subpage.html content. How do I fix this. Is it even possible to achieve this behaviour by default?

Upvotes: 7

Views: 2382

Answers (1)

mkopriva
mkopriva

Reputation: 38313

You could do something like this:

base.html

{{ define "top" }}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
{{ end }}

{{ define "bottom" }}
</body>
</html>
{{ end }}

home.html

{{ template "top" . }}

<div class="container mt-5">
    Hello
</div>

{{ template "bottom" . }}

subpage.html

{{ template "top" . }}

<div class="container">
    <div>
        <h2>This page is still in progress</h2>
    </div>
</div>

{{ template "bottom" . }}

Then make sure you're using the file's base name:

// in the home handler use the following
c.HTML(http.StatusOK, "home.html", data)

// in the subpage handler use the following
c.HTML(http.StatusOK, "subpage.html", data)

Upvotes: 5

Related Questions