From c565a9318a8ad96966d9777f7eaaf16a4b631fc5 Mon Sep 17 00:00:00 2001 From: Meutel Date: Fri, 4 Aug 2017 19:47:15 +0200 Subject: [PATCH] Templates func for book --- bouquins/bouquins.go | 14 ++++++++++++++ main.go | 4 ++-- templates/book.html | 5 +++-- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/bouquins/bouquins.go b/bouquins/bouquins.go index 5418742..a917b5a 100644 --- a/bouquins/bouquins.go +++ b/bouquins/bouquins.go @@ -3,9 +3,11 @@ package bouquins import ( "database/sql" "encoding/json" + "github.com/c2h5oh/datasize" "html/template" "log" "net/http" + "net/url" "strconv" "strings" ) @@ -180,6 +182,18 @@ func (app *Bouquins) render(res http.ResponseWriter, tpl string, model interface log.Print(err) } } +func TemplatesFunc() *template.Template { + tpl := template.New("") + tpl.Funcs(template.FuncMap{ + "humanSize": func(sz int64) string { + return datasize.ByteSize(sz).HumanReadable() + }, + "bookLink": func(data *BookData, book *BookFull) string { + return "/images/" + url.QueryEscape(book.Path) + "/" + url.QueryEscape(data.Name) + "." + strings.ToLower(data.Format) + }, + }) + return tpl +} func paramInt(name string, req *http.Request) int { val := req.URL.Query().Get(name) diff --git a/main.go b/main.go index 6019ff2..38406f2 100644 --- a/main.go +++ b/main.go @@ -3,7 +3,6 @@ package main import ( "database/sql" "encoding/json" - "html/template" "log" "net/http" "os" @@ -51,7 +50,8 @@ func initApp() *BouquinsConf { if err != nil { log.Fatalln(err) } - tpl, err := template.ParseGlob("templates/*.html") + + tpl, err := TemplatesFunc().ParseGlob("templates/*.html") if err != nil { log.Fatalln(err) } diff --git a/templates/book.html b/templates/book.html index 9fa9c0f..2090546 100644 --- a/templates/book.html +++ b/templates/book.html @@ -16,10 +16,11 @@ {{ if gt (len .Data) 0 }}
+ {{ $book := .BookFull }} {{ range .Data }} - + Télécharger - {{ .Format }} ({{ .Size }}) + {{ .Format }} ({{ humanSize .Size }}) {{ end }}