How do I pass a variable to the layout using Larav

2019-03-08 07:09发布

问题:

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?

回答1:

If you're using @extends in your content layout you can use this:

@extends('master', ['title' => $title])


回答2:

For future Google'rs that use Laravel 5, you can now also use it with includes,

@include('views.otherView', ['variable' => 1])


回答3:

I was able to solve that problem by adding this to my controller method:

    $title = 'My Title Here';
    View::share('title', $title);

$this->layout->title = 'Home page'; did not work either.



回答4:

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!



回答5:

It appears as though I can pass variables to the entire layout using attributes on the layout object, for example to solve my problem I was able to do the following:

$this->layout->title = 'Home page';


回答6:

Simplest way to solve:

view()->share('title', 'My Title Here');

Or using view Facade:

use View;

...

View::share('title', 'My Title Here');


回答7:

class PagesController extends BaseController {
    protected $layout = 'layouts.master';

    public function index()
    {
        $this->layout->title = "Home page";
        $this->layout->content = View::make('pages/index');
    }
}

At the Blade Template file, REMEMBER to use @ in front the variable.

...
<title>{{ $title or '' }}</title>
...
@yield('content')
...


回答8:

You can try:

public function index()
{
    return View::make('pages/index', array('title' => 'Home page'));
}


回答9:

$data['title'] = $this->layout->title = 'The Home Page';
$this->layout->content = View::make('home', $data);

I've done this so far because I needed in both the view and master file. It seems if you don't use $this->layout->title it won't be available in the master layout. Improvements welcome!