Is there a truncate modifier for the blade templates in Laravel, pretty much like Smarty?
I know I could just write out the actual php in the template but i'm looking for something a little nicer to write (let's not get into the whole PHP is a templating engine debate).
So for example i'm looking for something like:
{{ $myVariable|truncate:"10":"..." }}
I know I could use something like Twig via composer but I'm hoping for built in functionality in Laravel itself.
If not is it possible to create your own reusable modifiers like Smarty provides. I like the fact that Blade doesn’t overkill with all the syntax but I think truncate is a real handy function to have.
I'm using Laravel 4.
Limit string length in Blade You don't have to import the namespace as this is a global "helper" PHP function available out of the box with Laravel. Just change the $your_string part with your actual string and also the 50 part with the number of characters that you would like to limit your string to.
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.
In Laravel 4 & 5 (up to 5.7), you can use str_limit
, which limits the number of characters in a string.
While in Laravel 5.8 up, you can use the Str::limit
helper.
//For Laravel 4 to Laravel 5.5 {{ str_limit($string, $limit = 150, $end = '...') }} //For Laravel 5.5 upwards {{ \Illuminate\Support\Str::limit($string, 150, $end='...') }}
For more Laravel helper functions http://laravel.com/docs/helpers#strings
Laravel 4 has Str::limit
which will truncate to the exact number of characters, and also Str::words
which will truncate on word boundary.
Check out:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With