What is the purpose of the route name in mojolicious?

I learn how to program applications using the Mojolicious framework, and I am focused on why you use route names. For example, a route might 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'm new to web frameworks, so maybe this has a trivial answer.

+5
source share
1 answer

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

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

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

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

Then you can create a url like

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

$link /cities/newyork.

, , .

, , - . , , .

. Mojolicious.

+16

All Articles