Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of a route name in mojolicious?

I have been learning how to program apps using the Mojolicious framework and I am stumped as to why you use route names. For example a route could say

$r->route('/cities/new')
      ->via('get')
      ->to(controller => 'cities', action => 'new_form')
      ->name('cities_new_form');

But what is the purpose of the name parameter? I am new to web frameworks, so maybe this has a trivial answer to it.

like image 416
user1876508 Avatar asked Feb 15 '13 01:02

user1876508


1 Answers

Naming the route allows you to reference it later if you want to generate a URL dynamically. With your example, you could do this later in your code:

my $link = $self->url_for( 'cities_new_form' )

and $link would automatically be populated with a URL ending in /cities/new. You can get fancy if your route has dynamic parts. For example:

$r->route( '/cities/:cityname' )
    ->via( 'get' )
    ->to( controller => 'cities', action => 'new_form' )
    ->name( 'cities_new_form' );

Then you can generate a URL like

my $link = $self->url_for( 'cities_new_form', cityname => 'newyork' );

And $link would end up with /cities/newyork.

These are trivial examples, but you can build up fairly complex stuff once your routes get more involved.

If you don't name the route, it gets a default name which is just a concatenation of the alphanumeric characters in it. That can get tedious for long routes so you can use names to abbreviate them.

See also Named Routes in the Mojolicious documentation.

like image 77
friedo Avatar answered Nov 02 '22 23:11

friedo