Exploring Laravel's Custom Blade Directives
Earlier today, I was working on coding up a design that displays a varying number of cards - each with a unique title and description… think Masonry/Pinterest-esque. I’ve been using Model Factories to stub out a bunch of cards, all with different content. Once I’d hooked up the dummy data to the card templates, I realized that the design didn’t work as well with titles that had more than 20 or so characters.
A common solution to this would be to use CSS to break the line and automatically add an ellipsis like this:
.ellipsis {
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
However, this wouldn’t work well in my situation because the design allows titles to be two lines long.
Another solution would be to chop off the title at a given length and add an ellipsis using a php snippet like this:
$truncatedTitle = substr($title,0,20) . '...';
But, what if the title is less than 20 characters to start with? We wouldn’t want the snippet to add the ellipsis in that case.
$truncatedTitle = strlen($title) > 20 ? substr($title,0,20)."..." : $title;
By combining a string length check with a ternary operator, we can truncate and add the ellipsis if necessary. If the title is less than 20 characters, we just return it as normal.
None of this is very complicated if you are familiar with vanilla PHP.
However, adding this much PHP to my Blade templates would have really mucked up my otherwise-clean templates. So I decided to drop this functionality into a custom Blade directive that I could reuse where necessary.
Link: