简体   繁体   中英

Laravel Blade Passing Variables to Other Blades

I have tried a few things to try to get this to work. I was looking at this -- Laravel Blade - pass variable via an @include or @yield -- question about how to pass variables between blades but I can't seem to get it to work!

I have a view calling my header view (in /resources/views/layouts/frontendbasic.blade.php):

@include('common/head', array('url'=>'www.url.com'))

And in the header blade (in /resources/views/common/head.blade.php) I am calling that variable like this:

<meta property="og:url" content="{{ $url }}" />

And I get the error:

Undefined variable: url
(View: ...\resources\views\common\head.blade.php) 
(View: ...\resources\views\common\head.blade.php) 
(View: ...\resources\views\common\head.blade.php)

I am wondering what I am doing wrong?

The correct thing is to pass a variable through the controller:

return view('view.path', [
     'url' => 'www.url.com'
]);

however, try as below:

@include('common.head', ['url' => 'www.url.com'])

there are many way to done this. you can also use "compact" and "with" function for pass variable into blade in controller and blade also.

in controller

  $info = 23; /* variable you want to pass into blade */ 

  return view('view.path',compact('info'));
  OR
  return view('view.path')->with('info'=>$info);

in view

 @include('view.path',compact('variable_name'));
 OR
 @include('view.path')->with('key' => $value);

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