Reputation: 61
i'm trying to pass a variable to my 'master' layout :
//views/dashboard/layouts/master.blade.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
@yield('site.body');
{{{ isset($test) ? $title:'Test no exists :) ' }}}
</body>
</html>
Now in my DashboardController :
class DashboardController extends BaseController
{
public $layout = "dashboard.layouts.master";
// this throw error : Cannot call constructor
//public function __construct()
//{
// parent::__construct();
// $this->layout->title = 'cry...';
//}
// this throw error : Attempt to assign property of non-object
// and I understand it, coz $layout isn't an object
//public function __construct()
//{
// $this->layout->title = 'cry...';
//}
public function action_doIndex()
{
$this->layout->title = 'this is short title';
$this->layout->body = View::make('dashboard.index');
}
public function action_doLogin()
{
//$this->layout->title = 'this is short title'; // AGAIN ???
$this->layout->body = View::make('dashboard.forms.login');
}
public function action_doN()
{
// $this->layout->title = 'this is short title'; // AND OVER AGAIN ?!?!
}
}
I want set only ONCE the $title variable, and when I want to do it - overwrite it. Now I must set the variable every time when I call another method :/
How to do that ? How to set $title variable only ONCE for this 'master' layout ??
Symphony2 have before() / after() method - what laravel got ?
Upvotes: 2
Views: 4326
Reputation: 87719
You can use View::composer()
or View::share()
to "pass" variables to your views:
public function __construct()
{
View::share('title', 'cry...');
}
This is a composer:
View::composer('layouts.master', function($view)
{
$view->with('name', Auth::check() ? Auth::user()->firstname : '');
});
If you need it on all your views you can:
View::composer('*', function($view)
{
$view->with('name', Auth::check() ? Auth::user()->firstname : '');
});
You can even create a file for this purpose, something like app/composers.php
and load it in your app/start/global.php
:
require app_path().'/composers.php';
Upvotes: 8