我在 Larawel 的routes.php
上设置了一个资源,如下所示:
Route::resource('users', 'UsersController');
我创建了UsersController
,并将其设置为使用布局:
class UsersController extends BaseController {
protected $layout = 'layouts.default';
public function index()
{
$view = View::make('users.index');
$this->layout->title = "User Profile";
$this->layout->content = $view;
}
}
当我使用 http://localhost/myapp/users/index
访问它时,出现错误:
Undefined variable: title
但是如果我手动设置路线,例如:
Route::get('/users/index', array('as' => '/users/index', 'uses' => 'UsersController@index'));
它工作正常。
知道为什么会这样吗?
编辑:这些是视图
默认刀片.php
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>{{ $title }}</title>
<link rel="stylesheet" href="{{ asset('assets/css/style.default.css') }}" type="text/css" />
</head>
<body>
{{ $content }}
</body>
</html>
用户/索引.php
<div>
Some content ...
</div>
我认为
问题实际上在于你如何调用你的路线。
如果您查看文档 (http://laravel.com/docs/controllers#resource-controllers),您会发现没有用于/resource/index
的路由。这将被解析为/resource/{id}
其中$id="index",并将寻找一个show($id)
函数。 它知道它应该使用默认布局,但由于您没有设置标题的 show() 函数,因此没有标题传递给视图并且它爆炸了。
我敢打赌,如果你只是去http://localhost/myapp/users
,它会没事的。
class UsersController extends BaseController {
protected $layout = 'layouts.default';
public function index()
{
$data['title'] = "User Profile";
$this->layout->content = View::make('users.index')
->withData($data);
return $this->layout->content;
}
}
或
class UsersController extends BaseController {
protected $layout = 'layouts.default';
public function index()
{
$title = "User Profile";
$this->layout->content = View::make('users.index')
->withData($title);
return $this->layout->content;
}
}
但是使用$data数组很容易。在视图中使用它时,您可以按其名称引用它。所以$data['title']是用$title来称呼的。