martini-contrib / render

Martini middleware/handler for easily rendering serialized JSON, XML, and HTML template responses.
MIT License
245 stars 57 forks source link

Relative URL in template #34

Open yageek opened 10 years ago

yageek commented 10 years ago

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.

mickelsonm commented 10 years ago

@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.

yageek commented 10 years ago

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.

mickelsonm commented 10 years ago

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?