Skip to content

Instantly share code, notes, and snippets.

@SantosJMM
Last active March 31, 2020 02:17
Show Gist options
  • Save SantosJMM/493ca1d26b5373bd97fabc91ddfd3e59 to your computer and use it in GitHub Desktop.
Save SantosJMM/493ca1d26b5373bd97fabc91ddfd3e59 to your computer and use it in GitHub Desktop.
load parsed files into template go
package main
import (
"html/template"
"os"
"path/filepath"
)
// ParseTemplateDir parse dirs
// Example: var templates = template.Must(ParseTemplateDir("templates"))
func ParseTemplateDir(dir string) (*template.Template, error) {
var paths []string
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() {
paths = append(paths, path)
}
return nil
})
if err != nil {
return nil, err
}
return template.ParseFiles(paths...)
}
package main
import (
"os"
"testing"
)
type TemplateData struct {
SITENAME string
SITEURL string
}
func TestTemplateToHtml(t *testing.T) {
data := TemplateData{
SITENAME: "Theory and Practice",
SITEURL: "https://gist.github.com/",
}
tmpl, err := template.Must(ParseTemplateDir("templates"))
if err != nil {
t.Error(err)
}
err = tmpl.ExecuteTemplate(os.Stdout, "index.html", &data)
if err != nil {
t.Error(err)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment