[英]laravel compact() and ->with()
我有一段代碼,我試圖找出為什么一個變體有效而另一個無效。
return View::make('gameworlds.mygame', compact('fixtures'), compact('teams'))->with('selections', $selections);
這使我能夠按預期生成裝置、團隊和選擇的數組視圖。
然而,
return View::make('gameworlds.mygame', compact('fixtures'), compact('teams'), compact('selections'));
不允許正確生成視圖。 我仍然可以回顯數組並獲得預期的結果,但是一旦到達選擇部分,視圖就不會呈現。
沒關系,因為我讓它使用->with()
語法,但只是一個奇怪的語法。
謝謝。 DS
View::make
函數接受3 個參數,根據文檔是:
public View make(string $view, array $data = array(), array $mergeData = array())
在您的情況下, compact('selections')
是第四個參數。 它不會傳遞給視圖,並且 Laravel 會拋出異常。
另一方面,您可以根據需要多次使用with()
。 因此,這將起作用:
return View::make('gameworlds.mygame')
->with(compact('fixtures'))
->with(compact('teams'))
->with(compact('selections'));
我只是想跳到這里並更正(建議替代方案)上一個答案....
您實際上可以以相同的方式使用緊湊型,但是例如更整潔...
return View::make('gameworlds.mygame', compact(array('fixtures', 'teams', 'selections')));
或者,如果您使用的是 PHP > 5.4
return View::make('gameworlds.mygame', compact(['fixtures', 'teams', 'selections']));
這要簡潔得多,並且在查看應用程序的功能時仍然具有可讀性;)
我能夠使用
return View::make('myviewfolder.myview', compact('view1','view2','view3'));
我不知道是不是因為我使用的是 PHP 5.5 效果很好:)
Laravel 框架 5.6.26
返回多個數組然后我們使用compact('array1', 'array2', 'array3', ...)
返回視圖。
viewblade
是前端(視圖)刀片。
return view('viewblade', compact('view1','view2','view3','view4'));
您可以將變量數組作為參數傳遞給契約,例如:
return view('yourView', compact(['var1','var2',....'varN']));
鑒於:如果 var1 是一個對象,你可以像這樣使用它
@foreach($var1 as $singleVar1)
{{$singleVar1->property}}
@endforeach
標量變量的情況下,您可以簡單地
{{$var2}}
我已經這樣做了幾次沒有任何問題
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
或者
public function index($id)
{
$category = Category::find($id);
$topics = $category->getTopicPaginator();
$message = Message::find(1);
// here I would just use "->with([$category, $topics, $message])"
return View::make('category.index')->with(compact('category', 'topics', 'message'));
}
對我來說最好的方法:
$data=[
'var1'=>'something',
'var2'=>'something',
'var3'=>'something',
];
return View::make('view',$data);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.