grailsurl-mapping

Grails UrlMappings for unknown number of variables


I'm using url mappings to translate the URL directory structure into categories within a site, currently using:

class UrlMappings {

    static excludes = ['/css/*','/images/*', '/js/*', '/favicon.ico']
    static mappings = {       

        "/$category1?/$category2?/$category3?/"(controller: 'category')

        "500"(view:'/error')
        "404"(view:'/notFound')
    }
}

At present this supports categories three levels deep. I'd like to be able to support categories N levels deep where N >= 1.

How can this be achieved?


Solution

  • The asterisk, either single or double, is used for wilcard url mapping.

    A single asterisk will match anything at the given level:

    static mappings = {
        "/images/*.jpg"(controller:"image")
    }
    
    // Matches /images/logo.jpg, images/header.jpg and so on
    

    A double asterisk will match anything on more than one level:

    static mappings = {
        "/images/**.jpg"(controller:"image")
    }
    
    // Matches /images/logo.jpg, /images/other/item.jpg and so on
    

    Combined with the ? for optional mapping matches, the following will work in the context of the question:

    class UrlMappings {
    
        static excludes = ['/css/*','/images/*', '/js/*', '/favicon.ico', '/WEB-INF/*']
        static mappings = {
            "/**?"(controller: 'category')
    
            "500"(view:'/error')
            "404"(view:'/notFound')       
        }
    }