Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 875
Dwight Avatar asked Apr 20 '13 08:04

Dwight


People also ask

What is the advantage of Laravel blade template?

In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures while also remaining familiar to their PHP counterparts.

What is Template inheritance in Laravel blade?

A templating engine makes writing frontend code easier and helps in reusing the code. All the blade files have a extension of *. blade.


1 Answers

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> 
like image 180
s3v3n Avatar answered Sep 23 '22 11:09

s3v3n