2014-04-04 55 views
1

的最佳方法我是Laravel的新手,例如,如果我想在默認情況下在所有視圖中都有一個變量,是否有更好的方式比傳遞每次變化w/把一些變量放在Laravel-> Blade

return View::make('views_x.some_view')->with('client_to_show', $client_to_show); 

?或者比將它們存儲在Session中然後在視圖中訪問它們更好? 我試圖把變量佈局主:

//layout.master.blade.php on top 
<?php 
    $str_sel_names  = 'one_value'; 
?> 
<!-- starts template --> 
<!DOCTYPE html> 
<html lang="en"> 

但是這一次僅僅是模板佈局..不是子視圖裏面入店...

@extends('layouts.master')

@section('content') 
... 
{{$str_sel_names}} 

我得到:[ErrorException 未定義變量:str_sel_names(查看:C:\ Work \ lara_street \ laravel \ app \ views \ core \ dashboard.blade.php)]

想法?更好的方法來做到這一點?

+0

把它們在陣列中,或作爲一個StdClass對象的屬性,並傳遞到刀片 –

+0

酵母..但在這種情況下我瞭解我不得不通過它明確的觀點..一遍又一遍。 – rrubiorr81

回答

7

您可以使用View作曲家:

View::composer(['store.index', 'products.*'], function($view) 
{ 
    $view->with('client_to_show', $client_to_show); 
}); 

你可以把你的路線文件,過濾文件或一樣,我加入

require app_path().'/composers.php'; 

要創建app/composers.php和負載你app/start/global.php文件。

視圖共享是另一種選擇:

View::share('client_to_show', $client_to_show); 
+0

我應該在哪裏放置這個視圖::共享呼叫? – rrubiorr81

+1

取決於您如何獲取$ client_to_show的信息。但是你可以添加到你的控制器__construct(),但是如果這是全局的,你也可以使用像'app/composers.php'這樣的文件,正如我在上一個答案編輯中所說的那樣。 –

+0

thx,@Antonio ..!相當有用的信息.. – rrubiorr81