Search

Dark theme | Light theme

December 22, 2015

Ratpacked: Using Names With Regular Expression Tokens

In a previous post we have seen how to use regular expressions for path tokens. We can also name the path token for which the regular expression applies. This makes it easier to get the value in our handler code: we can just refer to the name. Also we can add a question mark to the name to make the token optional.

In the following example we use the name conferenceName for the path token with the regular expression Gr\w+:

import ratpack.groovy.template.MarkupTemplateModule
import ratpack.handling.Context
import ratpack.path.PathBinder
import ratpack.path.PathBinding

import static ratpack.groovy.Groovy.groovyMarkupTemplate
import static ratpack.groovy.Groovy.ratpack

ratpack {
    handlers {

        prefix('conferences') {
            // Here we define a path with the named 
            // token conferenceName.
            path(/:conferenceName:Gr\w+/) { 
                // The token has a name and a regular expression.
                // If the value matches the regular expression,
                // we can refer to the value using the name.
                final String conferenceName = pathTokens.conferenceName
                
                // Use matched value in response.
                render "Conference($conferenceName)"
            }
        }

    }
}

Written with Ratpack 1.1.1.