Skip to content

Instantly share code, notes, and snippets.

@phunguyen19
Last active October 8, 2024 13:38
Show Gist options
  • Save phunguyen19/ccb69679c6acabed29385f4a9ef15326 to your computer and use it in GitHub Desktop.
Save phunguyen19/ccb69679c6acabed29385f4a9ef15326 to your computer and use it in GitHub Desktop.
Go, Template, Helper Rendering
func snippetViewHandler(app *application) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
id, err := strconv.Atoi(r.PathValue("id"))
if err != nil || id < 1 {
app.clientError(w, http.StatusNotFound)
return
}
s, err := app.snippets.Get(id)
if err != nil {
if errors.Is(err, models.ErrNoRecord) {
app.clientError(w, http.StatusNotFound)
return
} else {
app.serverError(w, r, err)
return
}
}
app.render(w, r, 200, "view.tmpl", templateData{Snippet: s})
}
}
func (app *application) render(w http.ResponseWriter, r *http.Request, status int, page string, data templateData) {
ts, ok := app.templateCache[page]
if !ok {
app.serverError(w, r, fmt.Errorf("the template %s does not exist", page))
}
buf := new(bytes.Buffer)
err := ts.ExecuteTemplate(buf, "base", data)
if err != nil {
app.serverError(w, r, err)
return
}
w.WriteHeader(status)
buf.WriteTo(w)
}
func main() {
// ...
templateCache, err := newTemplateCache()
if err != nil {
logger.Error(err.Error())
os.Exit(1)
}
app := &application{
logger: logger,
snippets: &models.SnippetModel{DB: db},
templateCache: templateCache,
}
// ...
}
func newTemplateCache() (map[string]*template.Template, error) {
cache := map[string]*template.Template{}
pages, err := filepath.Glob("./ui/html/pages/*.tmpl")
if err != nil {
return nil, err
}
for _, page := range pages {
name := filepath.Base(page)
ts, err := template.ParseFiles("./ui/html/base.tmpl")
if err != nil {
return nil, err
}
ts, err = ts.ParseGlob("./ui/html/partials/*.tmpl")
if err != nil {
return nil, err
}
ts, err = ts.ParseFiles(page)
if err != nil {
return nil, err
}
cache[name] = ts
}
return cache, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment