render
render copied to clipboard
Relative URL in template
I use render to generate some basic HTML and I don't manage to create a relative URL to the current route without hardcoding all the URL.
For example I create a group "admin" and in the template I would like to create link without having to repeat "/admin" in the templates.
@yageek : There's many avenues you can take to construct the URL, but the main keywords that stuck out at me were "without having to repeat", which is a good indicator to use a method of some kind. Within that method you can pass in the URL, then do some logic on it to figure out when to append "/admin". I am unaware of your template usage, but if you're dealing with nested objects, then you may consider using a function map, which returns your constructed URL dynamically in the template.
What do you mean by using nested object ? I think that using a map[string][string]
and pass it as the template argument would works, but I wanted to arrive to something more simple.
I use the template basic system. I wanted to use the FuncMap
but I don't know how to get the current Route and the URL from the route.
I apologize if I caused any confusion, but all I meant by a nested object is if you had objects/fields within an object that you needed to check against.
Handler:
func MyHandler(rw http.ResponseWriter, req *http.Request, r render.Render) {
data := make(map[string]interface{})
data["CurrentUrl"] = req.URL
data["CurrentRoute"] = req.URL.Path
data["CheckAdminRoute"] = (req.URL.Path == "/test/admin")
r.HTML(http.StatusOK, "test", data)
}
Template:
{{if .CheckAdminRoute }}<p>You're on a admin route!</p>{{end}}
<p>Your URL is: {{.CurrentUrl}}</p>
<p>Your route is {{.CurrentRoute}}</p>
How about something like this?