func (t *Template) load(g *Group, name string, info interface{}) error { t.g = g // maybe create a setGroup method instead tmpl := template.New(name) tmpl.Funcs(g.funcs) var fm map[string]interface{} bytes, err := fmatter.ReadFile(filepath.Join(g.dir, name), &fm) if err != nil { return err } t.funcMap = template.FuncMap{ "page": func() interface{} { return fm }, } tmpl.Funcs(t.funcMap) ext := filepath.Ext(name) if ext == ".md" { bytes = blackfriday.MarkdownBasic(bytes) } _, err = tmpl.Parse(string(bytes)) if err != nil { return err } t.tmpl = tmpl if l, ok := fm["layout"]; ok { t.layout = l.(string) } else { t.layout = "default" } writeInfo(info, fm) return nil }
func TestTemplate(t *testing.T) { g := New("testdata/layouts") g.Clear() err := g.Glob("*.html") if err != nil { t.Fatal(err) } matter := make(map[string]interface{}) content, err := fmatter.ReadFile("testdata/index.html", matter) if err != nil { t.Fatal(err) } tmpl, err := template.New("index").Parse(string(content)) if err != nil { t.Fatal(err) } buf := bytes.NewBuffer(make([]byte, 0, 256)) data := map[string]interface{}{ "page": matter, } err = g.Execute(buf, matter["layout"].(string), tmpl, data) if err != nil { t.Fatal(err) } expected, err := ioutil.ReadFile("testdata/indexresult.html") if err != nil { t.Fatal(err) } actual, err := ioutil.ReadAll(buf) if err != nil { t.Fatal(err) } if bytes.Compare(expected, actual) != 0 { t.Fatal("result does not match!") } }
func (g *Group) load(filename string) error { front := make(map[string]interface{}, 4) content, err := fmatter.ReadFile(filename, front) if err != nil { return err } path := filename filename = filepath.Base(filename) ext := filepath.Ext(filename) name := filename[:len(filename)-len(ext)] _, ok := g.dict[name] if ok { return nil } var t *template.Template if g.tmpls == nil { t = template.New(name) g.tmpls = t t.Funcs(template.FuncMap{ "content": undefinedContent, }) t.Funcs(g.funcs) } else { t = g.tmpls.New(name) } _, err = t.Parse(string(content)) if err != nil { // hrm.. how do we remove a template..? return err } parent, _ := front["layout"].(string) g.dict[name] = Entry{unexportedEntry{t}, name, path, parent} return nil }