refactor: extract template rendering
This commit is contained in:
parent
3a0d758ef7
commit
d24f48bc52
2 changed files with 30 additions and 7 deletions
10
routes.go
10
routes.go
|
@ -5,7 +5,6 @@ import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/url"
|
"net/url"
|
||||||
"text/template"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type Link struct {
|
type Link struct {
|
||||||
|
@ -26,8 +25,7 @@ func healthcheck(w http.ResponseWriter, r *http.Request) {
|
||||||
//
|
//
|
||||||
// Static content for the about page.
|
// Static content for the about page.
|
||||||
func about(w http.ResponseWriter, r *http.Request) {
|
func about(w http.ResponseWriter, r *http.Request) {
|
||||||
tmpl, _ := template.New("about").ParseFiles("templates/about.html.tmpl", "templates/base.html.tmpl")
|
Render(w, "about", nil)
|
||||||
tmpl.ExecuteTemplate(w, "base", nil)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Feeds list
|
// Feeds list
|
||||||
|
@ -41,8 +39,7 @@ func listContent(w http.ResponseWriter, r *http.Request) {
|
||||||
links = append(links, formattedItems...)
|
links = append(links, formattedItems...)
|
||||||
}
|
}
|
||||||
|
|
||||||
tmpl, _ := template.New("base").ParseFiles("templates/index.html.tmpl", "templates/base.html.tmpl")
|
Render(w, "index", links)
|
||||||
tmpl.ExecuteTemplate(w, "base", links)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Manage content
|
// Manage content
|
||||||
|
@ -74,6 +71,5 @@ func manageContent(w http.ResponseWriter, r *http.Request) {
|
||||||
Feeds map[string]string
|
Feeds map[string]string
|
||||||
}
|
}
|
||||||
|
|
||||||
tmpl, _ := template.New("manage").ParseFiles("templates/manage.html.tmpl", "templates/base.html.tmpl")
|
Render(w, "manage", ManageTmplData{Feeds: allFeeds})
|
||||||
tmpl.ExecuteTemplate(w, "base", ManageTmplData{Feeds: allFeeds})
|
|
||||||
}
|
}
|
||||||
|
|
27
templates.go
Normal file
27
templates.go
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"path/filepath"
|
||||||
|
"text/template"
|
||||||
|
)
|
||||||
|
|
||||||
|
func Render(w io.Writer, templateName string, data interface{}) error {
|
||||||
|
asTemplatePath := func(templateName string) string {
|
||||||
|
return filepath.Join("templates", fmt.Sprintf("%s.html.tmpl", templateName))
|
||||||
|
}
|
||||||
|
|
||||||
|
templatePartials := []string{
|
||||||
|
asTemplatePath(templateName),
|
||||||
|
asTemplatePath("base"),
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpl, err := template.New(templateName).ParseFiles(templatePartials...)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tmpl.ExecuteTemplate(w, "base", data)
|
||||||
|
}
|
Loading…
Reference in a new issue