Using Named URL in blade template

2019-05-01 06:52发布

问题:

In Django, I can do this:

<a href="{% url 'account_login' %}">Account Link</a>

which would give me domain/account/login where I have that URL named in my urls.py

url(r'^account/login/$', views.Login.as_view(), name='account_login'),

I want to do something similar in Laravel 5.2

I currently have something like this:

Route::get('/survey/new', ['as' => 'new.survey', 'uses' => 'SurveyController@new_survey']);

How do I use in my template, plus passing in parameters?

I came across this: https://laravel.com/docs/5.1/helpers, but it was just a piece of a white page without relevant content of how to actually use it.

回答1:

You can use the route() helper, documented here.

<a href="{{ route('new.survey') }}">My Link</a>

If you include laravelcollective/html you could use link_to_route(). This was originally part of the core but removed in Laravel 5. It's explained here

{!! link_to_route('new.survey', 'My Link') !!}

The Laravel Collective have documented the aforementioned helper here. The function prototype is as follows

link_to_route($routeName, $title = null, $parameters = [], $attributes = []);

If for example you wanted to use parameters, it accepts an array of key value pairs which correspond to the named segments in your route URI.

For example, if you had a route

Route::get('surveys/{id}', 'SurveyController@details')->name('detail.survey');

You can generate a link to this route using the following in the parameters.

['id' => $id]

A full example, echoing markup containing an anchor to the named route.

{!! link_to_route('new.survey', 'My Link', ['id' => $id]) !!}