Using HTML Templates from a Folder (Complied)

· 120 words · 1 minute read

This will take all your templates (found within the templates folder) and add them to your executable application at compile time - so it’s fast as it doesn’t have to read from file. You can call these templates with ExecuteTemplate and passing the file name as the second parameter.

If you’re using this with a web server, you can replace the os.Stdout with the net/http writer.

package main

import (
    "html/template"
    "log"
    "os"
)

type Page struct {
    Title string
}

var templates = template.Must(template.ParseGlob("templates/*"))

func main() {

    p := Page{Title: "Heading"}
    err := templates.ExecuteTemplate(os.Stdout, "template.html", p)
    if err != nil {
        log.Fatal("Cannot Get View ", err)
    }

}
<!DOCTYPE html>
<html>
<head>
    <title>Template</title>
</head>
<body>
    <h1>Template {{.}}</h1>
</body>
</html>
Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!