What is the purpose of a route name in mojolicious?
Asked Answered
I

1

7

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.

Impassioned answered 15/2, 2013 at 1:26 Comment(0)
S
18

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.

Shrewsbury answered 15/2, 2013 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.