Home > Article > PHP Framework > Do you know these 5 very useful Blade commands?
The following is the Laravel Frameworktutorial column to introduce you to 5 very useful Blade instructions. I hope it will be helpful to friends in need!
Next I will introduce you to five Laravel Blade commands, which will make you even more powerful when solving specific problems. If you are new to Laravel, these tips can help you realize the convenience and efficiency of the Laravel Blade template engine.
Without further ado, let’s get started.
You can check whether the user is authenticated by verifying whether it is empty:
@if(auth()->user()) // 用户已认证 @endif
However, Laravel's own Blade command can be more concise To achieve the same function:
@auth // 用户已认证 @endauth
In contrast to authentication, we can use the auth
auxiliary function guest()
Method to detect whether the user is a guest:
@if(auth()->guest()) // 用户未认证 @endif
However, Laravel also provides the @guest
command:
@guest // 用户未认证 @endguest
We can also use else
statement to combine these two commands:
@guest // 用户未认证 @else // 用户已认证 @endguest
Building a multi-theme site may have a Do you know these 5 very useful Blade commands? if it exists Just introduce it, otherwise it will introduce another need. You can simply use conditional judgment to achieve it:
@if(view()->exists('first-view-name')) @include('first-view-name') @else @include('second-view-name') @endif
But there is still a more concise and intuitive command to do this:
@includeFirst(['first-view-name', 'second-view-name']);
When you only want to add some content based on certain logic (such as an authenticated user), introducing views based on conditions is very useful.
You can use @if
conditions to write like this:
@if($post->hasComments()) @include('posts.comments') @endif
We can do it with just one line of command @includeWhen
:
@includeWhen($post->hasComments(), 'posts.comments');
If you have a custom theme system or you need to dynamically create Blade views, then checking whether the Do you know these 5 very useful Blade commands? exists is a must.
You can call the exists
method on the auxiliary function view()
:
@if(view()->exists('view-name')) @include('view-name') @endif
You can also use the Blade command includeIf
Processing:
@includeIf('view-name')
You can learn more practical techniques to optimize the front-end template in your Laravel project through the Blade official documentation.
Happy refactoring!
Original address: https://laravel-news.com/five-useful-laravel-blade-directives
Translation address: https://learnku.com/laravel/ t/12328/5-very-useful-blade-designation-which-have-you-used
The above is the detailed content of Do you know these 5 very useful Blade commands?. For more information, please follow other related articles on the PHP Chinese website!