Laravel中的刀片模板是否有截断修改器,非常像Smarty?
我知道我可以在模板中写出实际的php,但我正在寻找一些更好的东西来编写(让我们不进入整个PHP是模板引擎的争论)。
所以例如我正在寻找类似的东西:
{{ $myVariable|truncate:"10":"..." }}
我知道我可以通过作曲家使用像Twig这样的东西,但我希望Laravel本身具有内置功能。
如果没有,可以创建自己的可重用修改器,如Smarty提供。我喜欢Blade不会过度使用所有语法的事实,但我认为truncate是一个非常方便的函数。
我正在使用Laravel 4。
在Laravel 4和5中,您可以使用str_limit
,它限制字符串中的字符数。
{{ str_limit($string, $limit = 150, $end = '...') }}
更多Laravel助手功能http://laravel.com/docs/helpers#strings
Laravel 4有Str::limit
,它将截断到确切的字符数,还有Str::words
,它将在字边界上截断。
查看:
编辑:这个答案是在Laravel 4 beta期间发布的,当时Str类不存在。现在有更好的方法在Laravel 4中完成 - 这是Dustin的答案如下。由于SO规则我不能删除这个答案(它不会让我)
刀片本身没有这种功能。
在Laravel 3中有Str类 - 你可以做到:
{{ Str::limit($myVariable, 10) }}
在这个阶段我不相信Str类在Laravel 4 - but here is a port of it that you can include in composer中添加到你自己的项目中
您可以设置命名空间,如:
{!! \Illuminate\Support\Str::words($item->description, 10,'....') !!}
要保持代码干净,如果您的内容来自您的模型,您应采用略有不同的方法。像这样编辑你的模型(在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, '...');
}
}
?>
然后在你看来:
{{ $comment->short_description }}
这适用于Laravel 5:
{!!strlen($post->content) > 200 ? substr($post->content,0,200) : $post->content!!}
Laravel 5.8更新
{!! Str::limit('Lorem ipsum dolor sit amet, consectetur adipisicing elit', 10, ' ...') !!}
产量
Lorem ipsu ...