我创建了一个名为(head.blade.php
)的视图,并尝试用View::make()
函数将其加载到HomeController __construct
函数中。然而,该函数是有效的,但不适用于变量。
例如,这里的函数,使用View::make()
:
public function __construct() {
$this->asset = new Asset;
$assets = array('core');
$css = $this->asset->generate($assets);
return View::make('includes.head')->with('styles', $css);
}
如果我试图在视图中使用$styles变量,它会给我错误:(未定义的变量$styles in…-)
但是,在Laravel文档中挖掘,我发现了这种方法:
public function __construct() {
$this->asset = new Asset;
$assets = array('core');
$css = $this->asset->generate($assets);
View::creator('includes.head', function($view) use ($css) {
$view->with('styles', $css);
});
}
方法CCD_ 5起作用。
我的问题是,View::make()
如何以及为什么不能在__construct
中工作?
PS。我正在用@include
方法调用另一个视图中的视图。
在一般OOP中,您不会从构造函数返回任何值。构造函数的隐式返回值是对象。请记住,每当创建新对象时都会调用构造函数:
$myObject = new MyObject(); // <-- I just called the MyObject constructor
Laravel控制器的实例化发生在路由调度之前,因此在构造函数中返回View在逻辑上是不正确的。另请参阅此答案。
我不知道你为什么要这么做,但我相信这可能是因为你试图将一个"头"视图附加到这个特定控制器返回的所有视图上。如果是这样的话,你在拉拉威尔就不是这样做的。要做到这一点,请制作一个布局视图,以便其他视图可以扩展:
<!-- app/views/layout/master.blade.php -->
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<article>
@include('layout.header')
@yield('content')
@include('layout.footer')
</article>
</body>
</html>
<!-- app/views/layout/header.blade.php -->
<header>
A Header
</header>
<!-- app/views/layout/footer.blade.php -->
<footer>
A Footer
</footer>
<!-- app/views/some-view.blade.php -->
@extends('layout.master')
@section('content')
View Content
@stop
有了这个设置,some-view.blade.php
将有一个页眉和一个页脚夹在视图的主要内容之间。