2016-10-19 17 views
1

子ビューを呼び出すIndexControllerのテンプレートビューファイルに$ stylesおよび$ scripts変数を渡すにはどうすればよいですか?私の現在のコードは、子ビューにのみデータを送信します。Laravel 5.3で作成したテンプレートファイルにデータを渡すには

class BaseController extends Controller 
{ 
    public $styles; 
    public $scripts; 

    public function __construct() 
    { 
     // Set styles and scripts 
     $this->styles = array(
      // css files go here 
     ); 
     $this->scripts = array(
      // js files go here 
     ); 
    } 
} 

class IndexController extends BaseController 
{ 
    // protected vars here 

    public function __construct(
     // interface files go here 
    ) 
    { 
     // vars here 

     // Append styles and scripts to existing parent array 
     parent::__construct(); 

     $this->styles['css goes here'] = 'screen'; 

     $this->scripts[] = 'js goes here'; 
    } 

    public function index() 
    { 
     View::make('index')->with('styles', $styles) 
       ->with('scripts', $scripts) 
    } 
} 

UPDATE:は私のビューファイルは、あなたがあなたに至る配列としてあなたの変数を渡すことができ

テンプレートビューファイル

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<meta name="viewport" content="width=device-width, initial-scale=1"> 
<meta name="robots" content="index, follow" /> 
<title>Title</title> 
@foreach($styles as $file => $type) 

    <link href="{{ $file}}" media="{{ $type }}" rel="stylesheet"> 

@endforeach 
@foreach($scripts as $file) 

    <script src="{{ $file }}"></script> 

@endforeach 
</head> 
<body> 
<div id="content"> 
    {{ $content }} 
</div> 
</body> 
</html> 

子ビューファイル

@extends('layout.template') 

@section('content') 
    // html for child view 
@endsection 

答えて

2

を追加しましたブレードテンプレートをデータパラメータに追加します。

public function index() 
    { 
     $styles = $this->styles; 
     $scripts = $this->scripts; 

     return view('index', compact($styles, $scripts)) 
    } 

EDIT

は、私はあなたがちょうどあなたの質問は、より理解しやすくするために、あなたのコードを短くしているかどうかわからないんだけど、ここで私はあなたが投稿コードで見ることができる問題の一部です:

$this index()中の

欠如:

あなた$styles$scriptsヴァリアークラス変数を取得するには、$this->styles$this->scriptsが必要です。

インデックス内のビューを()返さない:と

public function index() 
{ 
    return View::make('index')->with('styles', $this->styles) 
      ->with('scripts', $this->scripts) 
} 

降伏内容:は、あなたの指数関数は何も返していない

、ビューを返すためにreturnを追加する必要があります変数:

<div id="content"> 
    {{ $content }} 
</div> 

私には表示されません$contentビューに渡される変数は、おそらくビューコンポーザーのどこかにありますか?コンテンツを追加する通常の方法は、コンテンツセクションをビューに挿入するyieldを使用することです。

<div id="content"> 
    @yield('content') 
</div> 
+0

データをビューに渡す方法は分かっています。子ビューを呼び出すコントローラからテンプレートビューファイルにデータを渡す方法がわかりません。 – VenomRush

+0

それはあなたの全体の 'BaseController'ですか、それとも短縮しましたか?あなたが何をしようとしているのか分かりません。 –

+0

私のビューファイルを追加しました。私は$スタイルと$スクリプトを特定のコントローラで必要に応じて完全に上書きできるシナリオを説明しようとしています。 – VenomRush

関連する問題