Change default delimiters templating with “template.Delims”

A simple page

package mainimport (
"html/template"
"log"
"net/http"
)
type Infos struct {
Title, Content string
}
func main() {
port := ":3000"
log.Println("Starting Web Server 127.0.0.1" + port)

http.HandleFunc("/", indexHandler)

err := http.ListenAndServe(port, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
data := Infos{"Your title page", "A classic lorem ipsum content"}
pageFile := "index.html" tmpl, err := template.New(pageFile).Delims("[[", "]]").ParseFiles(pageFile) if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
tmpl.Execute(w, data)
}
<!DOCTYPE html>
<html>
<head>
<title>[[ .Title ]]</title>
</head>
<body>
<p>[[ .Content ]]</p></body>
</html>

A layout

In a layout, leave empty the “template.New()” string parameter.

package mainimport (
"html/template"
"log"
"net/http"
)
type Infos struct {
Title, Content string
}
func main() {
port := ":3000"
log.Println("Starting Web Server 127.0.0.1" + port)

http.HandleFunc("/", indexHandler)

if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}
func indexHandler(w http.ResponseWriter, r *http.Request) {
data := Infos{"Your title page", "A classic lorem ipsum content"}

tmpl, err := template.New("").Delims("[[", "]]").ParseFiles("layout.html", "index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
tmpl.ExecuteTemplate(w, "layout", data)
}
[[ define "layout" ]]<!DOCTYPE html>
<html>
<head>
<title>[[ .Title ]]</title>
</head>
<body>
[[ template "content" . ]]</body>
</html>
[[ end ]]
[[ define "content" ]]
<p>[[ .Content ]]</p>
[[ end ]]

--

--

A curious guy

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store