Truncate string in Laravel blade templates

后端 未结 11 1065
死守一世寂寞
死守一世寂寞 2020-12-07 15:28

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 looki

相关标签:
11条回答
  • 2020-12-07 15:47

    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 }}
    
    0 讨论(0)
  • 2020-12-07 15:50

    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>
    
    0 讨论(0)
  • 2020-12-07 15:54

    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

    0 讨论(0)
  • 2020-12-07 15:55

    This works on Laravel 5:

    {!!strlen($post->content) > 200 ? substr($post->content,0,200) : $post->content!!}
    
    0 讨论(0)
  • 2020-12-07 15:56

    You can Set the namespace like:

    {!! \Illuminate\Support\Str::words($item->description, 10,'....')  !!}
    
    0 讨论(0)
  • 2020-12-07 15:58

    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
    0 讨论(0)
提交回复
热议问题