Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Zaengle Blog:
Exploring Laravel's Custom Blade Directives
Mar 14, 2016 @ 18:38:30

On the Zaengle blog there's a post spotlighting the custom Blade directive functionality that comes with using the Blade templating engine of the Laravel framework. These allow the definition of custom functionality available directly from the templating layer.

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. [...] 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. [...] 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.

He shows how to define the custom Blade directive in the AppServiceProvider class (autoloaded with every request) for a simple "Hello World" example. He also shows how to use this in the template code, making a simple call to its matching helloWorld tag. He then implements his custom truncate handling, returning some simple PHP code that automatically reduces the content down to a given length and echoes out the result.

tagged: laravel custom blade directive tutorial helloworld truncate

Link: http://zaengle.com/blog/exploring-laravels-custom-blade-directives


Trending Topics: