如何从调用子视图的IndexController将$ styles和$ scripts变量传递给我的模板视图文件?我当前的代码只会将数据发送到子视图。
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)
}
}
更新:添加了我的观看文件
模板视图文件
<!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
答案 0 :(得分:3)
您可以将变量作为数组传递到刀片模板,方法是将其添加到数据参数中:
public function index()
{
$styles = $this->styles;
$scripts = $this->scripts;
return view('index', compact($styles, $scripts))
}
修改强>
我不确定您是否刚刚缩短了代码以使您的问题更容易理解,但以下是我发布的代码中可以看到的一些问题:
$this
中缺少index()
:
您的$styles
和$scripts
变量必须为$this->styles
和$this->scripts
才能获取类变量。
未在index()中返回视图:
你的索引函数没有返回任何内容,你需要添加return
来返回视图:
public function index()
{
return View::make('index')->with('styles', $this->styles)
->with('scripts', $this->scripts)
}
使用变量生成内容:
<div id="content">
{{ $content }}
</div>
我看不到传递给视图的$content
变量,也许它在视图作曲家的某个地方?但添加内容的常规方法是使用yield将内容部分注入到您的视图中:
<div id="content">
@yield('content')
</div>