Ad

Laravel Blade Variable Scope

- 1 answer

I am having trouble with variable scope in laravel blades when extending

home.blade.php (used by the controller):

@extends('templates.BaseBlade')

@section('head')
    <?php
    echo $testvar;
    ?>

BaseBlade.blade.php:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <?php
        $testvar = "this is a test";
    ?>

I was thinking that BaseBlade would be compiled, then $testvar should be accessible to home blade but this does not seem to happen in this order

Ad

Answer

So in laravel Blade templates, the scope of variable is passed from parents to children.


Inheritance of Blade tempalte

So if you start by returing a view like so:

return view('template-1')->with([
    'var1' => 'Test One',
    'var2' -> 'Test Two',
]);

In your blade template you can then echo these with the {{ }} syntax:

{{ $var1 }} # Test One
{{ $var2 }} # Test Two

Now say you are the using an @include, you will get both var1 & var2 in the scope and be able to override them an assign new variables to you include like so:

@include('_includes.include-1', ['var2' => 'Foo', 'var3' -> 'Bar'])
{{ $var1 }} # Test One
{{ $var2 }} # Foo
{{ $var3 }} # Bar

Now if you want to make a variable available to all blade templates which extend a given template (i.e. if "template-1" extends app). You can bind global variables in a ServiceProvider like so;

BladeServiceProvider

View::share('var4', 'Foo-Bar']);

Now you have access to var4 in all of your templates

{{ $var1 }} # Test One
{{ $var2 }} # Test Two
{{ $var4 }} # Foo-Bar
Ad
source: stackoverflow.com
Ad