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.
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:
and
$linkwould automatically be populated with a URL ending in/cities/new. You can get fancy if your route has dynamic parts. For example:Then you can generate a URL like
And
$linkwould 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.