在Laravel刀片模板中截断字符串 [英] Truncate string in Laravel blade templates

查看:530
本文介绍了在Laravel刀片模板中截断字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel中的刀片模板是否有截短修饰符,就像Smarty一样?

我知道我可以在模板中写出实际的php,但是我正在寻找更好的东西来写(关于整个PHP,这不是一个模板引擎辩论).

例如,我正在寻找类似的东西:

{{ $myVariable|truncate:"10":"..." }}

我知道我可以通过作曲家使用Twig之类的东西,但我希望Laravel本身具有内置功能.<​​/p>

如果不能,则可以创建自己的可重用修饰符,如Smarty提供的.我喜欢Blade并不会在所有语法上过大的事实,但是我认为truncate是一个真正方便的功能.

我正在使用Laravel 4.

解决方案

在Laravel 4& 5(最大5.7),可以使用str_limit,它限制了字符串中的字符数.

在Laravel 5.8及更高版本中,您可以使用Str::limit帮助器.

//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='...') }}

更多Laravel帮助器功能 http://laravel.com/docs/helpers#strings

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.

解决方案

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刀片模板中截断字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆