Prevent overwriting of blocks with same name in Go Template

Viewed 31

I'm having difficulty in rendering the correct content using templates in Go. Either case of navigating to /about or / the same content is getting rendered. Below is the current state of code.

I have read that you can parse templates in each handleFunc (for each request) but that seems to be an inefficient way to mitigate the issue.


Code

I have the following templates

  • base
  • header
  • footer
  • index
  • about
{{ define "base"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Project Website</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/water.css@2/out/water.css">
</head>
<body>
    {{template "header" .}}
    {{template "body" .}}
    {{template "footer" .}}
</body>
</html>
{{end}}
{{define "header"}}
<h1>Header</h1>
{{end}}
{{define "footer"}}
<h1>Footer</h1>
{{end}}
{{template "base" .}}
{{define "body"}}
<h1>About</h1>
{{end}}
{{template "base" .}}
{{define "body"}}
<h1>Index</h1>
{{end}}

main.go

package main

import (
    "html/template"
    "log"
    "net/http"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseGlob("templates/*"))
}

func main() {
    // Connect to database.

    // Routes
    http.HandleFunc("/about", about)
    http.HandleFunc("/", index)
    http.HandleFunc("/favicon.ico", doNothing) // TODO Replace with something like do not found

    // Listen and serve.
    log.Fatal(http.ListenAndServe(":8000", nil))
}

// TODO go away
func doNothing(w http.ResponseWriter, r *http.Request) {}

handlerFunctions.go

package main

import (
    "log"
    "net/http"
)

func index(rw http.ResponseWriter, req *http.Request) {
    log.Println("Index page called")
    tpl.ExecuteTemplate(rw, "index.gohtml", nil)
}

func about(rw http.ResponseWriter, req *http.Request) {
    log.Println("About page called")
    tpl.ExecuteTemplate(rw, "about.gohtml", nil)
}
0 Answers
Related