ChatGPT解决这个技术问题 Extra ChatGPT

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.

what about laravel 5 ?
I hope and pray that you are not working on laravel 4 anymore. :D
@Vipertecpro hehe, wouldn't that be something! Laravel has come a long way since.

E
Etin

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


Correct answer since use case is in Blade view.
In version 5.8 str helpers got removed you must use Illuminate\Support\Str::limit($string) instead
str_limit is deprecated
First 3 characters: {{ \Illuminate\Support\Str::limit($string, 0, 3) }}
J
Jon

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


Do you know if an equivalent of Str::words exist in Larvel 5.2 ?
No. Looks like it limits number of words now, not characters. github.com/laravel/framework/blob/5.2/src/Illuminate/Support/…
That was what I was looking for ! Thx !
L
Laurence

Edit: This answer is was posted during the Laravel 4 beta, when Str class did not exist. There is now a better way to do it in Laravel 4 - which is Dustin's answer below. I cannot delete this answer due to SO rules (it wont let me)

Blade itself does not have that functionality.

In Laravel 3 there was the Str class - which you could do:

{{ Str::limit($myVariable, 10) }}

At this stage I do not believe the Str class is in Laravel 4 - but here is a port of it that you can include in composer to add to your own project


Thanks for the suggestion, seems I will have to cave in and use the Meido ports lol
Nowadays Laravel 4 has the Str class. See Dustin Graham's response.
Yes - that is correct. When I originally posted this answer it was during Laravel 4 Beta, when the Str class did not exist
Where is the origianl answer? Its freaking impossible to find any docs for 4.1 now... :(
V
Vipertecpro

Update for Laravel 7.*: Fluent Strings i.e a more fluent, object-oriented interface for working with string values, allowing you to chain multiple string operations together using a more readable syntax compared to traditional string operations.

limit Example :

$truncated = Str::of('The quick brown fox jumps over the lazy dog')->limit(20);

Output

The quick brown fox...

words Example :

$string = Str::of('Perfectly balanced, as all things should be.')->words(3, ' >>>');

Output

Perfectly balanced, as >>>

Update for Laravel 6.* : You require this package to work all laravel helpers composer require laravel/helpers

For using helper in controller, don't forget to include/use class as well

use Illuminate\Support\Str;

Laravel 5.8 Update

This is for handling characters from the string :

{!! Str::limit('Lorem ipsum dolor', 10, ' ...') !!}

Output

Lorem ipsu ... 

This is for handling words from the string :

{!! Str::words('Lorem ipsum dolor', 2, ' ...') !!}

Output

Lorem ipsum ... 

Here is the latest helper documentation for handling string Laravel Helpers


very clean solution. worked for me. best answer IMO
@maximus1127 Thank you so much for your efforts towards learning, I'm glad I can be useful for you.
Great! Kind of answer i'd love to see more.
What will happen it you have string like Lorem ipsum's dolor will it return correct result ?
@Rishi Yes it will return the correct result, btw which method are you talking about limit ? or words ?
G
Guillaume Pommier

To keep your code DRY, and if your content comes from your model you should adopt a slightly different approach. Edit your model like so (tested in L5.8):

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class Comment extends Model
{
    public function getShortDescriptionAttribute()
    {
        return Str::words($this->description, 10, '...');
    }
}
?>

Then in your view :

{{ $comment->short_description }}

R
Raman Bhasker

You can Set the namespace like:

{!! \Illuminate\Support\Str::words($item->description, 10,'....')  !!}

I
ItalyPaleAle

For simple things like this I would prefer to make a helper - for example:

create a helpers.php file in your /app/helpers.php with following content:

<?php
if (! function_exists('short_string')) {
    function short_string($str) {
            $rest = substr($str, 0, 10);
            return $rest;
    }
}

Register the helper.php at autoload in your composer.json

   "autoload": {
        "files": [
            "app/helpers.php"
        ],
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    }

After that you can use in your blade file for example:

{{ short_string($whatever_as_text) }}

You can use this simple function, then, globally in your app.


B
Blue

This works on Laravel 5:

{!!strlen($post->content) > 200 ? substr($post->content,0,200) : $post->content!!}

G
Ganesh Khadka

You can set string limit as below example:

<td>{{str_limit($biodata ->description, $limit = 20, $end = '...')}}</td>

It will display only the 20 letters including whitespaces and ends with ....

https://i.stack.imgur.com/3f05O.png


S
Simone Rossaini

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 7 up, you can use the Str::limit helper.

//For Laravel  to Laravel 7

{{ Illuminate\Support\Str::limit($post->title, 20, $end='...') }}

Laravel 7, use only {{ Str::limit($chamado->subClient->name, 10) }}
W
WalterV

You can use sub_str:

{{substr($myVariable,10)}}

M
MRMP

The Str::words method limits the number of words in a string. An additional string may be passed to this method via its third argument to specify which string should be appended to the end of the truncated string:

use Illuminate\Support\Str;

return Str::words('Perfectly balanced, as all things should be.', 3, ' >>>');

// Perfectly balanced, as >>>

You may pass a third argument to the method to change the string that will be appended to the end of the truncated string:

use Illuminate\Support\Str;

$truncated = Str::limit('The quick brown fox jumps over the lazy dog', 20, ' (...)');

// The quick brown fox (...)

S
Shamsheer

Laravel 6 Update:

@php
$value = 'Artificial Intelligence';
$var = Str::limit($value, $limit = 15, $end = '');
print_r($var);
@endphp

<p class="card-text">{{ Illuminate\Support\Str::limit($value, 7) }}</p>
<h2 class="main-head">{!! Str::limit($value, 5) !!}</h2>

a
arba-67

The example below, work with laravel 8.

{!! Str::words("$post->content", 8, ' ...') !!}

{!! Str::limit("$post->content", 15, ' ...') !!}


K
Karl Hill

You can use the Laravel Blade directive like this.

Str::limit('$yourString',numberOfElement).

For example Str::limit('Test', 3) will show you Tes...