1. Introduction
Blade is a simple but very powerful templating engine created and bundled with Laravel. Unlike other templating engines, Blade does not prohibit you from using plain PHP in your views.
All Blade views are compiled into plain PHP code and cached until modified, meaning Blade basically does not increase any initial cost in the application.
Blade also provides us with a feature when working with loop structures that is the $ loop variable. This variable provides us with some useful information such as the current loop index or if this is the first or las element in the loop.
Today I will introduce a pretty cool and interesting function of $ loop is using even and odd flags .
2.Get started
When you apply an HTML file, the CSS file in the blade file sometimes comes across situations where you need to check the parity of the returned data loop to filter the background color code or something that matches the designing UI . .
In Laravel’s Blade view, one way to achieve this is to customize the following code:
1 2 3 4 5 6 7 8 9 10 | @foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->iteration % 2 == 0) This is an even iteration @else This is an odd iteration @endif @endforeach @endforeach |
Syntax as you can see, it looks quite dense and not very professional. But, Laravel has something neater and better to do that.
Using even and odd flags
1 2 3 4 5 6 7 8 9 10 | @foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->even) This is an even iteration @elseif ($loop->odd) This is an odd iteration @endif @endforeach @endforeach |
In addition, the $ loop variable has many other useful properties:
3.Conclusion
The use of Blade templete is very simple and convenient, so it has greatly increased larravel’s power.
Hopefully the article will help those who need it, you can also learn more about such convenient features here .