The must have PHP ternary rescue helper
Rendering stuffs conditionally is the most common job for programmers of any language and when it comes to PHP developers, the sight of html all mixed up with php logic is πͺ. .. (..you know)
π₯½ If you are familiar with Vue or Alpine JS for handling class attribute value they use a neat syntax, which is something like this ___
you pass in an object whose keys are class names, and values are boolean expressions to determine if those class names are applied or not
β‘ Here is how weβll commonly do the equivalent in PHP β -
. . . and its dirty π·
π Here comes the tiny utility function to save our lives β -
the concept is same, you pass an associative array where the key is the string to render & the value stands as boolean expression to resolve whether the string to be rendered / printed (for current example html class attribute value)
and use it as β¦
the readability is much better & looks neat π
π‘ Tip: If you use Laravel β -
we can create a string macro on Illuminate\Support\Str helper class to make things tidy, here is how :-
in app/Providers/AppServiceProvider.php or if you have any other custom Provider class, go to the boot method
now you can use in your blade view as Str::classNames([ β¦
π Before finishing
This quick tip is heavily inspired by Alpine JS and a recent great pull request made to Laravel core framework where I found this technique.
very soon youβll be able to write something similar for blade-x components in Laravel as the pull request got merged.
<div {{ $attributes->class(['p-4', 'bg-red' => $hasError]) }}>