[Dancer-users] Routing: captures in prefix

David Precious davidp at preshweb.co.uk
Fri Aug 19 14:14:05 CEST 2011


On Friday 19 August 2011 10:16:51 Michele Beltrame wrote:
> Hello!
> 
> I'm just beginning with Dancer - looks like a great framework to me -
> and I have a question. I have the following code:
> 
> ------------------
> package stelage::products;
> use Dancer ':syntax';
> 
> get '/:lang/products/' => sub {
>     return vars->{lang} . ' is the language';
> };
> ------------------
> 
> This works and allows me to use URIs such as:
> 
> myapp/it/products/
> myapp/en_US/products/
> 
> etc...
> 
> I'd like, however, some more automation on this by using the "prefix"
> keywords, but it doesn't seem to work with prefixes. So, this:
> 
> ------------------
> prefix '/:lang/products';
> 
> get '/' => sub {
>     return vars->{lang} . ' is the language';
> };
> ------------------
> 
> doesn't match. I also tried with regular expressions in routes, but
> didn't work either.


You're right, you won't be able to use a prefix that way.

One possible way would be to use a before hook to take the language out of the 
URL, maybe something like the following (untested):

hook before => sub {
    my $path = request->path_info;
    my ($lang) = $path =~ s{/(.+)/}{/};
    vars->{lang} = $lang;
    request->path_info($path);
}

Then, your routes can just use e.g. get '/products' => sub {...}, and the 
language that was removed from the beginning of the URL will be available in 
vars->{lang} within the route handler.

Cheers

Dave P


-- 
David Precious  ("bigpresh")
http://www.preshweb.co.uk/

   "Programming is like sex. One mistake and you have to support
   it for the rest of your life". (Michael Sinz)


More information about the Dancer-users mailing list