restructure page

This commit is contained in:
Henrique Dias
2016-06-23 22:27:13 +01:00
parent 07b6459e54
commit 8b7c83539a
6 changed files with 150 additions and 198 deletions

60
page.go
View File

@@ -12,7 +12,6 @@ import (
// Page contains the informations and functions needed to show the page
type Page struct {
Info *PageInfo
Tpl *template.Template
}
// AssetFunc is an Assets function
@@ -72,37 +71,38 @@ func (p PageInfo) PreviousLink() string {
return parts[len(parts)-2]
}
// AddTemplate adds a template file to the page template
func (p *Page) AddTemplate(name string, assets AssetFunc, functions template.FuncMap) (int, error) {
// Get the template from the assets
page, err := assets("templates/" + name + ".tmpl")
// Check if there is some error. If so, the template doesn't exist
if err != nil {
log.Print(err)
return http.StatusInternalServerError, err
}
// If it's the first iteration, creates a new template and add the
// functions map
if p.Tpl == nil {
p.Tpl, err = template.New(name).Funcs(functions).Parse(string(page))
} else {
p.Tpl, err = p.Tpl.Parse(string(page))
}
if err != nil {
log.Print(err)
return http.StatusInternalServerError, err
}
return 0, nil
}
// PrintAsHTML formats the page in HTML and executes the template
func (p Page) PrintAsHTML(w http.ResponseWriter) (int, error) {
func (p Page) PrintAsHTML(w http.ResponseWriter, templates ...string) (int, error) {
templates = append(templates, "actions", "base")
var tpl *template.Template
// For each template, add it to the the tpl variable
for i, t := range templates {
// Get the template from the assets
page, err := Asset("templates/" + t + ".tmpl")
// Check if there is some error. If so, the template doesn't exist
if err != nil {
log.Print(err)
return http.StatusInternalServerError, err
}
// If it's the first iteration, creates a new template and add the
// functions map
if i == 0 {
tpl, err = template.New(t).Parse(string(page))
} else {
tpl, err = tpl.Parse(string(page))
}
if err != nil {
log.Print(err)
return http.StatusInternalServerError, err
}
}
buf := &bytes.Buffer{}
err := p.Tpl.Execute(buf, p.Info)
err := tpl.Execute(buf, p.Info)
if err != nil {
return http.StatusInternalServerError, err