How do I pass a variable to the layout using Laravel' Blade templating?
In Laravel 4, my controller uses a Blade layout:
class PagesController extends BaseController {
protected $layout = 'layouts.master';
}
The master layout has outputs the variable title and then displays a view:
...
<title>{{ $title }}</title>
...
@yield('content')
....
However, in my controller I only appear to be able to pass variables to the subview, not the layout. For example, an action could be:
public function index()
{
$this->layout->content = View::make('pages/index', array('title' => 'Home page'));
}
This will only pass the $title
variable to the content section of the view. How can I provide that variable to the whole view, or at the very least the master layout?
If you're using @extends
in your content layout you can use this:
@extends('master', ['title' => $title])
Note that same as above works with children, like:
@include('views.subView', ['my_variable' => 'my-value'])
Usage
Then where variable is passed to, use it like:
<title>{{ $title ?? 'Default Title' }}</title>
For future Google'rs that use Laravel 5, you can now also use it with includes,
@include('views.otherView', ['variable' => 1])
In the Blade Template : define a variable like this
@extends('app',['title' => 'Your Title Goes Here'])
@section('content')
And in the app.blade.php or any other of your choice ( I'm just following default Laravel 5 setup )
<title>{{ $title or 'Default title Information if not set explicitly' }}</title>
This is my first answer here. Hope it works.Good luck!