Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate string in Laravel blade templates

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.

like image 607
fl3x7 Avatar asked Feb 21 '13 21:02

fl3x7


People also ask

How do I limit words in Laravel blade?

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.

What is Blade template in Laravel?

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.


2 Answers

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

like image 93
Anil Singh Avatar answered Sep 23 '22 13:09

Anil Singh


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:

  • http://laravel.com/api/4.2/Illuminate/Support/Str.html#method_limit
like image 32
Dustin Graham Avatar answered Sep 23 '22 13:09

Dustin Graham