Templates func for book

This commit is contained in:
Meutel 2017-08-04 19:47:15 +02:00
parent cfdd62f125
commit c565a9318a
3 changed files with 19 additions and 4 deletions

View File

@ -3,9 +3,11 @@ package bouquins
import ( import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"github.com/c2h5oh/datasize"
"html/template" "html/template"
"log" "log"
"net/http" "net/http"
"net/url"
"strconv" "strconv"
"strings" "strings"
) )
@ -180,6 +182,18 @@ func (app *Bouquins) render(res http.ResponseWriter, tpl string, model interface
log.Print(err) 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 { func paramInt(name string, req *http.Request) int {
val := req.URL.Query().Get(name) val := req.URL.Query().Get(name)

View File

@ -3,7 +3,6 @@ package main
import ( import (
"database/sql" "database/sql"
"encoding/json" "encoding/json"
"html/template"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -51,7 +50,8 @@ func initApp() *BouquinsConf {
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }
tpl, err := template.ParseGlob("templates/*.html")
tpl, err := TemplatesFunc().ParseGlob("templates/*.html")
if err != nil { if err != nil {
log.Fatalln(err) log.Fatalln(err)
} }

View File

@ -16,10 +16,11 @@
</div> </div>
{{ if gt (len .Data) 0 }} {{ if gt (len .Data) 0 }}
<div class="col-xs-12 col-md-3 text-right"> <div class="col-xs-12 col-md-3 text-right">
{{ $book := .BookFull }}
{{ range .Data }} {{ range .Data }}
<a :href="bookLink(book, data)" class="btn btn-success"> <a href="{{ bookLink . $book }}" class="btn btn-success">
<span class="glyphicon glyphicon-download-alt"></span> Télécharger <span class="glyphicon glyphicon-download-alt"></span> Télécharger
{{ .Format }} ({{ .Size }}) {{ .Format }} ({{ humanSize .Size }})
</a> </a>
{{ end }} {{ end }}
</div> </div>