Html template returns text instead of html

I’ve the below code:

package main

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

var templatesHtml *htmlTempl.Template
var err error

func init() {
	fmt.Println("Starting up.")
	templatesHtml = htmlTempl.Must(htmlTempl.ParseGlob("templates/*.html"))
}

func test(w http.ResponseWriter, r *http.Request) {
	err = templatesHtml.ExecuteTemplate(w, "other.html", nil)
	if err != nil {
		log.Fatalln(err)
	}
}

func main() {
	server := http.Server{
		Addr: "127.0.0.1:8080",
	}
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./public"))))
	http.HandleFunc("/test", test)
	server.ListenAndServe()
}

And my templates are:

// Content of base.html:
{{define "base"}}
<html>
  <head>{{template "head" .}}</head>
  <body>{{template "body" .}}</body>
</html>
{{end}}

And

// Content of other.html:
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}

The output I got at http://127.0.0.1:8080/test is:

enter image description here

While I was expecting normal HTML page to be displayed!

I found it, the error was in using // as comment markers, it had be solved by replacing them with the html content comment marker as below:

<!-- Content of other.html: -->
{{template "base" .}}
{{define "head"}}<title>other</title>{{end}}
{{define "body"}}other{{end}}

And it is working fine now.

1 Like