createLink
Purpose
Creates a link that can be used where necessary (for example in an href, javascript, ajax call etc.)Examples
Example controller for an application called "shop":class BookController {
def defaultAction="list"
def list = { [ books: Book.list( params ) ] }
def show = { [ book : Book.get( params['id'] ) ] }
} Example usages for above controller:<g:createLink action="show" id="1" /> == /shop/book/show/1
<g:createLink controller="book" /> == /shop/book
<g:createLink controller="book" action="list" /> == /shop/book/list
<g:createLink url="[action:'list',controller:'book']" /> == /shop/book/list
Example as a method call in GSP:<a href="${createLink(action:'list')}">my link</a> Results in:<a href="/shop/book/list">my link</a>
Description
Attributes
action (optional) - the name of the action to use in the link, if not specified the default action will be linked
controller (optional) - the name of the controller to use in the link, if not specified the current controller will be linked
id (optional) - The id to use in the link
url (optional) - A map containing the action,controller,id etc.
Source
Show Source
def createLink = { attrs ->
// prefer a URL attribute
def urlAttrs = attrs
if(attrs['url'] instanceof Map) {
urlAttrs = attrs.remove('url').clone()
}
else if(attrs['url']) {
urlAttrs = attrs.remove('url').toString()
} if(urlAttrs instanceof String) {
out << response.encodeURL(urlAttrs)
}
else {
def controller = urlAttrs.containsKey("controller") ? urlAttrs.remove("controller") : grailsAttributes.getController(request)?.controllerName
def action = urlAttrs.remove("action")
def id = urlAttrs.remove("id")
def frag = urlAttrs.remove('fragment')
def params = urlAttrs.params && urlAttrs.params instanceof Map ? urlAttrs.remove('params') : [:] if(urlAttrs.event) {
params."_eventId" = urlAttrs.event
}
def url
if(id != null) params.id = id
def urlMappings = applicationContext.getBean("grailsUrlMappingsHolder")
def mapping = urlMappings.getReverseMapping(controller,action,params)
url = mapping.createURL(controller, action, params, request.characterEncoding, frag)
if (attrs.base) {
out << attrs.remove('base')
} else {
handleAbsolute(attrs)
}
out << response.encodeURL(url)
} }