abstract from beego, part of its template.
SIMPLATE would load all template files in ViewsPath, and keep all template.Template, indexed by VIEW-PATH-NAME, in map. SIMPLATE can avoid loading template file repeatly into memory, to save time.
import "github.com/chalvern/simplate"
SIMPLATE has a variable named ViewsPath
keep the template's directory.
SIMPLATE will load all template files in the ViewsPath
into memory.
IMPORTANT layout file must contains {{ .LayoutContent }}
as its body, like:
<html>
<head>
<style type="text/css">
body {background-color: red}
p {margin-left: 20px}
</style>
</head>
<body>
{{ if .LayoutContent }}{{ .LayoutContent }} {{ end }}
</body>
</html>
the body content would be nested into layout as LayoutContent
.
import "github.com/chalvern/simplate"
func InitIsmplate(){
simplate.ViewsPath = "your-templates-dir" // default is "views"
simplate.LayoutFile = "your-layout-file" // default is "layout/default.html"
// if there are some template functions
// such as the data format function
dataFormatFunc := func(t time.Time) string {
return t.UTC().Format("2006年01月02日03时04分05秒UTC")
}
simplate.AddFuncMap("dataFormat", dataFormatFunc)
// initial
simplate.InitTemplate()
}
func YourCode() error {
data := make(map[string]interface{})
// data["Jingwei"] = "https://jingwei.link"
return simplate.ExecuteTemplate(os.Stdout,"home/body.html", data)
}
func YourCodeTwo() error {
data := make(map[string]interface{})
data["layout"] = "layout/default.html"
// data["site"] = "https://WhereSmile.com"
return simplate.ExecuteTemplate(os.Stdout,"home/body.html", data)
}
func YourCodeThree() error {
data := make(map[string]interface{})
// data["site"] = "https://WhereSmile.com"
return simplate.ExecuteViewPathTemplateWithLayout(os.Stdout, "layout/default.html", "home/body.html", data)
}
SIMPLATE keeps all template.Template in private variable simplateViewPathTemplates
.
As your template dir hierarchy as:
views
|--home
|--index.html
|--head.tpl
|--body.tpl
|--layout
|--default.html
the keys of simplateViewPathTemplates
would be []string{"home/body.tpl","home/head.tpl","home/index.html","layout/default.html"}
.
Finally, enjoy your coding.