While perhaps not as powerful as the Twig template engine, Laravel's Blade template engine does pretty much everything you're likely to need done in your view templates and it does it with more intuitive syntax. So I wanted to give it some props here that it very much deserves.
To boil Blade down to its very basics, there are three essential construct types you need to know:
To boil Blade down to its very basics, there are three essential construct types you need to know:
- {{ $var }} - output a variable
- {!! $html !!} - output some HTML (previously sanitized, we hope)
- @something - the equivalent of the if/else/foreach statements in PHP
Basically, any PHP statement you need to use will work within the body of these three constructs. So here are some control flow statements in Blade:
@foreach ($companies as $i => $company)
@endforeach
@if ($something === null)
@endif
And here are three versions of an echo statement that all work the same:
{{ $name === null ? 'Unknown Name' : $name }}
{{ $name or 'Unknown Name' }}
{{ $name ?? 'Unknown Name' }}
(Note: this last statement requires PHP7+)
Why is all this important? The main benefit here is in keeping your output statements very simple. After all, you want your view template to be all about the HTML, not the underlying code.
As an example of a real-life benefit, here's an issue I ran across recently:
When beginning a project, the client specified that they needed to know whether a person owned or rented their property. So I created a boolean field called "own". If not owned, then rented...right?
Nearing project completion, the client tells me that they need to also know if the question wasn't answered. So now we have three states...own, rented and null. Rather than ditch my boolean field, I can take advantage of the nullable property of the database field. Unfortunately, the backend database and O/S that hosts this application differ from development to staging/production, so I can't guarantee that the model's value will return NULL, a boolean, an integer or string. Thankfully, all I have to do is update my blade statement, like so:
{{ $own === null || $own === "" ? "" : $own == 1 ? "Own" : "Rent" }}
Smooth...
Comments
Post a Comment