Identifying even and odd iterations in Laravel Blade

Tram Ho

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:

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

In addition, the $ loop variable has many other useful properties:


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 .

Share the news now

Source : Viblo