Skip to content

Commit

Permalink
feat: setup block content in template + add new funcmap + set context…
Browse files Browse the repository at this point in the history
… (request) in funcmap + configure active menu + port the 'copaings' page
  • Loading branch information
moul committed Jan 22, 2019
1 parent 223885d commit bd6a56e
Show file tree
Hide file tree
Showing 7 changed files with 205 additions and 72 deletions.
2 changes: 2 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@ require (
github.com/grpc-ecosystem/grpc-gateway v1.6.4
github.com/jtolds/gls v4.2.1+incompatible // indirect
github.com/moul/numberinfo v0.0.0-20160903151149-753f372df509
github.com/moul/sprig v0.0.0-20170404194836-dba49a8d3a46
github.com/oxtoacart/bpool v0.0.0-20150712133111-4e1c5567d7c2
github.com/pkg/errors v0.8.1
github.com/satori/go.uuid v1.2.0 // indirect
github.com/shazow/memoizer v0.0.0-20130904030615-74fc48eaeadc
github.com/sirupsen/logrus v1.3.0 // indirect
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d // indirect
Expand Down
3 changes: 3 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,8 @@ github.com/moul/advanced-ssh-config v2.8.0+incompatible h1:TwBlAP+vrtYVW+cv+NJqG
github.com/moul/advanced-ssh-config v2.8.0+incompatible/go.mod h1:R4jFrcdiyzi23qjl7fBUyk7zV3xoFv5S8ulBBsU2ufw=
github.com/moul/numberinfo v0.0.0-20160903151149-753f372df509 h1:I9dq1rfaqOuM/cdoYtHeAK/nJxU2iRJAx9MPwHjoJic=
github.com/moul/numberinfo v0.0.0-20160903151149-753f372df509/go.mod h1:9J61gswx3x7Sv1flRnwrSJv0jIksuHecefKXOnjMBpI=
github.com/moul/sprig v0.0.0-20170404194836-dba49a8d3a46 h1:unq5acwmnJ+T7/c8TFry3PsBIvKag9OLpg+pGPZP9BA=
github.com/moul/sprig v0.0.0-20170404194836-dba49a8d3a46/go.mod h1:L1YcYiORJV//vKELNvA8LX4T+WSIa2z6zz9kgd6mUMg=
github.com/nicksnyder/go-i18n v1.10.0/go.mod h1:HrK7VCrbOvQoUAQ7Vpy7i87N7JZZZ7R2xBGjv0j365Q=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.7.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
Expand All @@ -285,6 +287,7 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.0.0 h1:o4VLZ5jqHE+HahLT6drNtSGTrrUA3wPBmtpgqtdbClo=
github.com/rogpeppe/go-internal v1.0.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/satori/go.uuid v1.2.0 h1:0uYX9dsZ2yD7q2RtLRtPSdGDWzjeM3TbMJP9utgA0ww=
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
github.com/serenize/snaker v0.0.0-20171204205717-a683aaf2d516/go.mod h1:Yow6lPLSAXx2ifx470yD/nUe22Dv5vBvxK/UK9UUTVs=
github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo=
Expand Down
33 changes: 32 additions & 1 deletion templates/copaings.tmpl
Original file line number Diff line number Diff line change
@@ -1,5 +1,36 @@
{{define "title"}}Copaings{{end}}
{{define "h1"}}Des copaings{{end}}
{{define "h1small"}}d'amour{{end}}

{{define "content"}}
Copaingzzz
{{ $square_size := 250 }}

<h4>Les sites d'internet des copaings</h4>
<div class="row">
{{ range $key, $copain := .friends }}

<div class="col-xs-12 col-sm-6 col-md-4 col-lg-4 rotate-random">
<div class="thumbnail"
width="{{$square_size}}" height="{{$square_size}}">
<div class="caption-wrapper">
<div class="caption">
<h4>{{ $copain.Name }}</h4>
<h5>{{ $copain.Description }}</h5>
<hr />
{{ range $link := $copain.Links }}
<a class="btn btn-primary"
href="{{ $link.URL }}"
target="_blank">
{{ $link.Name }}
</a>
{{ end }}
</div>
</div>
<img src="{{ $copain.ImageURL | cache_external_assets | resize (printf "%dx%d" $square_size $square_size) "fill=1" }}"
class="img-responsive" width="{{$square_size}}" height="{{$square_size}}" />
</div>
</div>

{{ end }}
</div>
{{end}}
17 changes: 8 additions & 9 deletions templates/layout/base.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -80,25 +80,25 @@
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="{{ if eq active_page "home" }}active {{ end }}">
<li class="{{ if eq active_menu "home" }}active {{ end }}">
<a href="/" class="disco">Maizon</a>
</li>
<li class="{{ if eq active_page "muzik" }}active {{end}}">
<li class="{{ if eq active_menu "muzik" }}active {{end}}">
<a href="/muzik" class="disco">Muzik</a>
</li>
<li class="{{ if eq active_page "hackz" }}active {{end}}">
<li class="{{ if eq active_menu "hackz" }}active {{end}}">
<a href="/hackz" class="disco">Hackz</a>
</li>
<!--<li class="{{ if eq active_page "vidz" }}active {{end}}">
<!--<li class="{{ if eq active_menu "vidz" }}active {{end}}">
<a href="/vidz" class="disco">Vidz</a>
</li>-->
<li class="{{ if eq active_page "copaings" }}active {{end}}">
<li class="{{ if eq active_menu "copaings" }}active {{end}}">
<a href="/copaings" class="disco">Copaings</a>
</li>
<!--<li class="{{ if eq active_page "tofz" }}active {{end}}">
<!--<li class="{{ if eq active_menu "tofz" }}active {{end}}">
<a href="/tofz" class="disco">Tofz</a>
</li>-->
<!--<li class="{{ if eq active_page "concertz" }}active {{end}}">
<!--<li class="{{ if eq active_menu "concertz" }}active {{end}}">
<a href="/concertz" class="disco">Concertz</a>
</li>-->
</ul>
Expand All @@ -111,9 +111,8 @@

<div class="col-xs-12 col-sm-12 col-md-9 col-lg-9 col-md-push-3 col-lg-push-3">
<div class="row">
THE CONTENT
{{ block "content" . }}{{end}}
{{/*
{{ block "content" . }}
{{ if layout == 'two_columns' }}
<div class="col-xs-12 col-sm-12 col-md-8 col-lg-8">
<h1>{{ self.title() }} <small>{{ self.subtitle() }}</small></h1>
Expand Down
95 changes: 64 additions & 31 deletions views/funcmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,69 +3,102 @@ package views
import (
"html/template"
"math/rand"
"net/http"

"go.uber.org/zap"
"github.com/moul/sprig"
"ultre.me/calcbiz/pkg/random"
)

func getFuncmap(opts *Options) template.FuncMap {
f := funcmap{opts: opts}
return template.FuncMap{
"yomyman_style": f.yomymanStyle,
"devel": f.devel,
"sharing_image_url": f.sharingImageURL,
"sharing_description": f.sharingDescription,
"current_url": f.currentURL,
"active_page": f.activePage,
"resize": f.resize,
"page_title": f.pageTitle,
"invalid_cache": f.invalidCache,
"logo_alternate": random.AlternateLogo,
"mot_du_jour": random.WOTD,
"megahertz": f.megahertz,
"mot_debile_qui_se_mange": random.MotDebileQuiSeMange,
"neige": func() bool { return false },
}
func getFuncmap(opts *Options) *ctxFuncmap {
f := &ctxFuncmap{opts: opts}

fm := sprig.FuncMap()
fm["yomyman_style"] = f.yomymanStyle
fm["devel"] = f.devel
fm["sharing_image_url"] = f.sharingImageURL
fm["sharing_description"] = f.sharingDescription
fm["current_url"] = f.currentURL
fm["active_page"] = f.activePage
fm["active_menu"] = f.activeMenu
fm["resize"] = f.resize
fm["page_title"] = f.pageTitle
fm["invalid_cache"] = f.invalidCache
fm["logo_alternate"] = random.AlternateLogo
fm["mot_du_jour"] = random.WOTD
fm["megahertz"] = f.megahertz
fm["mot_debile_qui_se_mange"] = random.MotDebileQuiSeMange
fm["neige"] = func() bool { return false }
fm["cache_external_assets"] = f.cacheExternalAsset
f.fm = fm
return f
}

type funcmap struct{ opts *Options }
type ctxFuncmap struct {
fm template.FuncMap
opts *Options
req *http.Request
}

func (f *funcmap) devel() bool { return f.opts.Debug }
func (f *ctxFuncmap) devel() bool { return f.opts.Debug }

func (f *funcmap) sharingImageURL() string {
func (f *ctxFuncmap) sharingImageURL() string {
return "http://www.camembertaulaitcrew.biz/static/img/logo-300.png" // FIXME: make it dynamic
}

func (f *funcmap) activePage() string { return "home" } // FIXME: make it dynamic
func (f *ctxFuncmap) activePage() string {
return f.req.URL.Path
}

func (f *ctxFuncmap) activeMenu() string {
switch f.req.URL.Path {
case "/":
return "home"
case "/muzik":
// FIXME: support albums, songs
return "muzik"
case "/copaings":
return "copaings"
case "/hackz":
// FIXME: support hackz URLs
return "hackz"
default:
return "home"
}
}

func (f *funcmap) pageTitle() string { return "Camembert au lait crew" } // FIXME: make it dynamic
func (f *ctxFuncmap) pageTitle() string { return "Camembert au lait crew" } // FIXME: make it dynamic

func (f *funcmap) sharingDescription() string { return "c'est cool" }
func (f *ctxFuncmap) sharingDescription() string { return "c'est cool" }

func (f *funcmap) currentURL() string {
func (f *ctxFuncmap) currentURL() string {
return "https://www.camembertaulaitcrew.biz/"
// FIXME: make it flexible (should be canonical url
}

func (f *funcmap) resize(opts ...string) string {
func (f *ctxFuncmap) cacheExternalAsset(path string) string {
// FIXME: implement
return path
}

func (f *ctxFuncmap) resize(opts ...string) string {
path := opts[len(opts)-1]
opts = opts[:len(opts)-1]
zap.L().Debug("redize", zap.String("path", path), zap.Strings("opts", opts))
//zap.L().Debug("resize", zap.String("path", path), zap.Strings("opts", opts))
// FIXME: apply transform + cache + give new URL
return path
}

func (f *funcmap) yomymanStyle() string {
func (f *ctxFuncmap) yomymanStyle() string {
styles := []string{"cachou", "jambon", "epinard", "lasagne", "haricot", "sandwich"}
return "cool-style-" + styles[rand.Intn(len(styles))]
}

func (f *funcmap) invalidCache() string {
func (f *ctxFuncmap) invalidCache() string {
// FIXME: use random string (once per server start)
// FIXME: or create a new func that returns file content hash
return "no_cache_please"
}

func (f *funcmap) megahertz() float64 {
func (f *ctxFuncmap) megahertz() float64 {
return rand.Float64() * 100
}
34 changes: 24 additions & 10 deletions views/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var (
bufpool *bpool.BufferPool
)

func loadTemplates(opts *Options) error {
func (h *handlers) loadTemplates() error {
box = packr.NewBox("../templates")
bufpool = bpool.NewBufferPool(64)
templates = make(map[string]*template.Template)
Expand All @@ -40,8 +40,8 @@ func loadTemplates(opts *Options) error {
}

// generate optimized templates
funcmap := getFuncmap(opts)
mainTemplate := template.New("main").Funcs(funcmap)
h.funcmap = getFuncmap(h.opts)
mainTemplate := template.New("main").Funcs(h.funcmap.fm)
mainTemplate = template.Must(mainTemplate.Parse(`{{define "main"}}{{template "base" .}}{{end}}`))
mainTemplate = template.Must(mainTemplate.Parse(layoutContent))
for filepath, content := range pageContents {
Expand All @@ -52,35 +52,49 @@ func loadTemplates(opts *Options) error {
return nil
}

func setDefaultHeaders(w http.ResponseWriter) {
push(w, "/css/calc.css")
func (h *handlers) setDefaultHeaders(w http.ResponseWriter) {
h.push(w, "/css/calc.css")
w.Header().Set("Content-Type", "text/html; charset=utf-8")
}

func renderError(w http.ResponseWriter, r *http.Request, err error) {
func (h *handlers) renderError(w http.ResponseWriter, r *http.Request, err error) {
zap.L().Warn("rendering error", zap.Error(err))
http.Error(w, fmt.Sprintf("Error: %v\n", err), http.StatusInternalServerError)
}

func render(w http.ResponseWriter, r *http.Request, name string, data interface{}) {
func (h *handlers) render(w http.ResponseWriter, r *http.Request, name string, data renderData) {
tmpl, ok := templates[name]
if !ok {
renderError(w, r, fmt.Errorf("the template %s does not exist.", name))
h.renderError(w, r, fmt.Errorf("the template %s does not exist.", name))
return
}

buf := bufpool.Get()
defer bufpool.Put(buf)

if data == nil {
data = make(renderData)
}

data["req"] = map[string]interface{}{
"name": name,
"r": r,
}

// set current request in ctxFuncmap objects
h.mutex.Lock()
defer h.mutex.Unlock()
h.funcmap.req = r

if err := tmpl.Execute(buf, data); err != nil {
renderError(w, r, err)
h.renderError(w, r, err)
return
}

buf.WriteTo(w)
}

func push(w http.ResponseWriter, resource string) {
func (h *handlers) push(w http.ResponseWriter, resource string) {
pusher, ok := w.(http.Pusher)
if ok {
if err := pusher.Push(resource, nil); err == nil {
Expand Down
Loading

0 comments on commit bd6a56e

Please sign in to comment.