Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Blade inline if and else if statement

Is there a syntax to specify inline if and else if statement in Laravel blade template?

Normally, the syntaxt for if and else statement would be :

{{ $var === "hello" ? "Hi" : "Goodbye" }} 

I would now like to include else if statement, is this possible?

 {{ $var === "hello" ? "Hi" : "Goodbye" else if $var ==="howdie ? "how" : "Goodbye""}} 
like image 289
mario Avatar asked Mar 26 '17 04:03

mario


People also ask

How do you check if a variable is empty in laravel?

Assumption #1: You Know The Variable Exists Within The View. REMEMBER: an empty array will always return false. Therefore, there is no real need to run it through a function like empty or is null. Comparing it to null will tell you if it exists or not.

How do you check if a variable is set or not in laravel?

You can use the @isset blade directive to check whether the variable is set or not.

What is Blade file in laravel?

Introduction. Blade is the simple, yet powerful templating engine that is included with Laravel. Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates.


2 Answers

You can use this code in laravel blade:

{{  $var === "hello" ? "Hi" : ($var ==="howdie ? "how" : "Goodbye") }} 
like image 116
MoPo Avatar answered Sep 19 '22 21:09

MoPo


remember not every short code is a good one. in your example there's no single way to hit this else if because you're saying

if($var === "hello")     {          // if the condetion is true         "Hi";     } else     {          // if the condetion is false         "Goodbye";     } // error here else if($var ==="howdie")     { "how"; } else     { "Goodbye"; } 

this's wrong you can't use two elses respectively. you've structure your conditions like

if (condition) {     # code... } elseif (condition) {     # code... } else {  } 

the same in the ternary operators

(condition) ? /* value to return if first condition is true */  : ((condition) ? /* value to return if second condition is true */  : /* value to return if condition is false */ ); 

and beware of (,) in the second condition.

and as you see your code is just going to be tricky, unreadable and hard to trace. so use the if else if if you've more than one condition switching and revise your logic.

like image 39
M.Elwan Avatar answered Sep 22 '22 21:09

M.Elwan