谢谢你的阅读。我是Laravel公司的新手,我想尝试用@foreach刀片来更改数据库的输出,下面是一个例子:
这是路线:
Route::get('/home', 'warnajati@index');我是主计长:
public function index()
{
$post = DB::table('posts')->get();
return view('warnajati', ['posts'=>$post]);
}以下是意见:
@foreach ($posts as $post)
<div class="title"><h3>{{$post->title}}</h3></div>
@endforeach使用$post->title的输出是"This is The Looonger Title you ever know",我想用"This is The Looonger Title you ever know"函数使标题更短:
function wordlimit($text, $limit=10)
{
if (strlen($text)>$limit) {
# code...
$word = mb_substr($text,0,$limit-3)."...";
}else{
$word =$text;
}
};我必须如何和在哪里将这一功能放在拉拉项目中??请帮帮我..。
发布于 2016-11-16 14:57:05
你的函数没有返回值。Laravel已经具备了以下功能:http://laravel.com/docs/5.3/helpers#method-str-limit
@foreach ($posts as $post)
<div class="title"><h3>{{ str_limit($post->title, 10) }}</h3></div>
@endforeach发布于 2016-11-16 14:57:35
您可以使用Laravel's Accessor在模型中这样做:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function getShortTitleAttribute($value)
{
// return shortened title here ...
}
}然后你可以像这样在刀刃上使用它:
{{ $post->short_title }}希望这能有所帮助!
发布于 2016-11-16 15:02:22
您可以将函数放在库文件夹中的helpers.php文件中。只需确保helpers.php文件在composer.json文件中自动加载:
"autoload": {
"files": [
"libraries/helpers.php"
],
},如果您必须将此添加到您的composer.json中,您还必须从终端运行composer dump-autoload命令。
https://stackoverflow.com/questions/40635185
复制相似问题