简体   繁体   中英

Laravel: Can't use @include blade variable into its parent blade

I am facing a problem with the scope of the laravel blade file. The variable set inside the @include blade can't be used in its parent blade. For example

child.blade.php

$myVar = "foo";

And then in the parent.blade.php

@include('child') {{-- including the child blade. --}}
{{ $myVar }}   {{-- printing the child blade variable --}}

Undefined variable: myVar in view parent.blade.php

I have tried this solution but I still can't modify the variable inside my child blade.

Calling a variable in parent file which was initialized in child file, doesn't make sense.

What you can do is create the variable on parent blade file using and pass to child.


@php($variable = 'test')
@include('child', ['variable' => $variable]) // Passing variable to child blade file.

{{ $variable }}

In Laravel if you want to access variable then you have to pass it into that function which will be in controller using compact()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM