Example #1
0
//loadTemplate 加载解析模板
func (d *dynamic) loadTemplate(currDir string) (*template.Template, error) {
	if len(d.Template) == 0 {
		return nil, fmt.Errorf(ErrorPageNotTemplate)
	}
	var (
		t                           *template.Template = nil
		filePath, fileName, content string
		b                           []byte
		err                         error
	)

	for _, filename := range d.Template {
		filePath = filepath.Join(currDir, filename)
		fileName = filepath.Base(filename)

		b, err = ioutil.ReadFile(filePath)
		if err != nil {
			return nil, err
		}
		content = d.formatTemplate(string(b))

		var tmpl *template.Template
		if t == nil {
			t = template.New(fileName)
		}
		if fileName == t.Name() {
			tmpl = t
		} else {
			tmpl = t.New(fileName)
		}
		tmpl.Delims(d.Delims.Left, d.Delims.Right)
		tmpl.Funcs(TemplateFuncMap)
		_, err = tmpl.Parse(content)
		if err != nil {
			return nil, err
		}
	}
	return t, nil
}