diff --git a/lib/template.go b/lib/template.go index 2720039..ae8e311 100644 --- a/lib/template.go +++ b/lib/template.go @@ -8,8 +8,10 @@ import ( "encoding/json" "errors" + "fmt" "io" "net/http" + "net/url" "path" "strings" "time" @@ -17,6 +19,11 @@ import ( "gitlab.com/trantor/trantor/lib/database" ) +var tmpl_funcs = map[string]interface{}{ + "strings_join": stringsJoin, + "download_url": downloadUrl, +} + type Status struct { BaseURL string FullURL string @@ -68,14 +75,12 @@ func InitTemplate(assetsPath string) *Template { var t Template templatePath := path.Join(assetsPath, "templates") - t.html, err = html_tmpl.New("html").Funcs(html_tmpl.FuncMap{ - "strings_join": strings.Join, - }).ParseGlob(path.Join(templatePath, "*.html")) + t.html, err = html_tmpl.New("html").Funcs(tmpl_funcs).ParseGlob(path.Join(templatePath, "*.html")) if err != nil { log.Critical("Error loading html templates: ", err) } - t.opds, err = txt_tmpl.ParseGlob(path.Join(templatePath, "*.opds")) + t.opds, err = txt_tmpl.New("opds").Funcs(tmpl_funcs).ParseGlob(path.Join(templatePath, "*.opds")) if err != nil { log.Critical("Error loading opds templates: ", err) } @@ -83,6 +88,15 @@ func InitTemplate(assetsPath string) *Template { return &t } +func stringsJoin(strs []string) string { + return strings.Join(strs, ", ") +} + +func downloadUrl(book database.Book) string { + fileName := url.PathEscape(fmt.Sprintf("%s - %s.epub", strings.Join(book.Authors, ", "), book.Title)) + return fmt.Sprintf("/download/%s/%s", book.ID, fileName) +} + type DevTemplateExecutor struct { assetsPath string tpe string @@ -106,11 +120,9 @@ func (e DevTemplateExecutor) ExecuteTemplate(wr io.Writer, name string, data int for _, f := range []string{"header.html", "footer.html", "book_list.html"} { included_files = append(included_files, path.Join(templatePath, f)) } - t = html_tmpl.Must(html_tmpl.New("html").Funcs(html_tmpl.FuncMap{ - "strings_join": strings.Join, - }).ParseFiles(included_files...)) + t = html_tmpl.Must(html_tmpl.New("html").Funcs(tmpl_funcs).ParseFiles(included_files...)) case "txt": - t = txt_tmpl.Must(txt_tmpl.ParseFiles(file)) + t = txt_tmpl.Must(txt_tmpl.New("txt").Funcs(tmpl_funcs).ParseFiles(file)) } return t.ExecuteTemplate(wr, name, data) } diff --git a/templates/book.html b/templates/book.html index c1b7fca..83f7dd0 100644 --- a/templates/book.html +++ b/templates/book.html @@ -50,7 +50,7 @@ function delBook(){