Grails UrlMappings for unknown number of variables

1.8k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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')       
    }
}
0
On

This question is ancient but in the url mappings you can also do this

"/categories/$categories**?"(controller:categories)

this will load the rest of the uri into param variable

  /categories/animals/dogs/retrievers

  ///goes to categories controller and has...
  params.categories //= "animals/dogs/retrievers"

You could then use that to do various dynamic things