使用 Laravel 显示博客文章摘录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19766636/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:37:33  来源:igfitidea点击:

Show blog post excerpt with Laravel

phplaravel

提问by 303K

I'm trying to show the excerptsfrom blog posts. I am able to do this with phpand mysql. However, I am wondering if there is a more 'friendly' way of doing this within the Laravel framework.

我正在尝试展示excerpts来自博客文章的内容。我可以用phpand做到这一点mysql。但是,我想知道在 Laravel 框架内是否有一种更“友好”的方式来做到这一点。

Thanks!

谢谢!

回答by Aatish Sai

You can do it using the method words

您可以使用该方法来完成 words

Default is:

默认为:

 words($value,$words = 100, $end='...');

You can implement it like this

你可以像这样实现它

Str::words($post->body);

Str::words($post->body,10); //will show first 10 words

回答by Muhammad Sheraz

Sorry I am very late but hope that it will help someone:

对不起,我来晚了,但希望它会帮助某人:

Using it like this may throw "Class 'Str' not found error":

像这样使用它可能会抛出“找不到类‘Str’错误”:

Str::words($post->body,10);

Use along with complete namespace, like this:

与完整的命名空间一起使用,如下所示:

\Illuminate\Support\Str::words($post->body, 10);

OR with dots:

或带点:

\Illuminate\Support\Str::words($post->body, 10,'...');

OR register the function as Facade in config/app.php, try adding it like this way:

或者在config/app.php 中将该函数注册为 Facade ,尝试像这样添加它:

'aliases' => [
...
        'Str' => Illuminate\Support\Str::class,
...
]

And then use Str::any where!, and hence you are free you use: Str::words($post->body,10);

然后使用Str::任何地方!,因此您可以自由使用: Str::words($post->body,10);

Need short and neat solution, just use Laravel's str_limit()helper function:

需要简洁的解决方案,只需使用 Laravel 的str_limit()辅助函数:

str_limit($post->body, 10);

OR

或者

str_limit($post->body, 10,'...');

回答by m3esma

You can use str_limiteasily.

您可以str_limit轻松使用。

Inside the PHP files:

在 PHP 文件中:

str_limit($value, $limit = 100, $end = '...')

Inside the Blade Templatesfiles:

刀片模板文件中:

{{ str_limit($value, $limit = 100, $end = '...') }}

I saw that this is available from version 4.2to 5.6

我看到从4.25.6版本都可以使用

Reference

参考