Skip to content

Instantly share code, notes, and snippets.

@cryptix
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save cryptix/11531399 to your computer and use it in GitHub Desktop.

Select an option

Save cryptix/11531399 to your computer and use it in GitHub Desktop.
Martini Route/Render TemplateFuncs issue
package main
import (
"github.com/go-martini/martini"
"github.com/martini-contrib/render"
"html/template"
)
var templateFuncs = template.FuncMap{
// define an empty stub first, otherwise html/template will complain with "missing function"
"whereAmI": func() string {
return ""
},
}
// middleware to inject the route
func HelperFuncs() martini.Handler {
return func(ren render.Render, route martini.Route) {
ren.Template().Funcs(injectHelperFuncs(route))
}
}
// create the real template helpers
var injectHelperFuncs = func(r martini.Route) template.FuncMap {
templateFuncs["whereAmI"] = func() string {
// use the user object defined outside, closures are awesome!
return r.GetName()
}
return templateFuncs
}
func main() {
m := martini.Classic()
m.Use(render.Renderer(render.Options{
Directory: ".",
Funcs: []template.FuncMap{templateFuncs},
}))
m.Use(HelperFuncs())
m.Get("/test1", func(ren render.Render, route martini.Route) {
ren.HTML(200, "main", nil)
}).Name("Test1")
m.Get("/test2", func(ren render.Render, route martini.Route) {
ren.HTML(200, "main", nil)
}).Name("Test2")
m.Run()
}
<html>
<head>
<title>Route/Render Test</title>
</head>
<body>
<h1>Hi</h1>
<p>You are here:{{whereAmI}}</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment