Last active
August 29, 2015 14:00
-
-
Save cryptix/11531399 to your computer and use it in GitHub Desktop.
Martini Route/Render TemplateFuncs issue
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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