Home:ALL Converter>Laravel 4 Blade @include variable

Laravel 4 Blade @include variable

Ask Time:2014-01-17T17:35:02         Author:user1995781

Json Formatter

I was trying to do include with Laravel blade, but the problem is it can't pass the variable. Here's my example code:

file_include.blade.php

<?php
  $myvar = "some text";

main.blade.php

@include('file_include')
{{$myvar}}

When I run the file, it return the error "Undefined variable: myvar". So, how can I pass the variable from the include file to the main file?

Thank you.

Author:user1995781,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/21182399/laravel-4-blade-include-variable
Kenny :

Why would you pass it from the include to the calling template? If you need it in the calling template, create it there, then pass it into the included template like this:\n\n@include('view.name', array('some'=>'data'))\n\n\nAbove code snippet from http://laravel.com/docs/templates",
2014-03-17T19:47:15
ErcanE :

Unfortunately Laravel Blade engine doesn't support what you expected!.But a little traditional way you can achieve this!\n\nSOLUTION 1 - without Laravel Blade Engine\n\nStep a:\n\nfrom\n\nfile_include.blade.php\n\n\nto\n\nfile_include.php\n\n\nStep b:\n\nmain.blade.php\n\n<?php \n include('app/views/file_include.php')\n?>\n{{$myvar}}\n\n\n\n\nSOLUTION 2 with Laravel Blade Engine\n\nroutes.php\n\n$data = array(\n'data1' => \"one\",\n'data2' => \"two\",\n);\n\nView::share('data', $data); \n\n\nAccess $data array from Any View like this\n\n{{ $data['data1'] }}\n\n\nOutput\n\none\n",
2015-02-27T19:05:10
Shubhamoy :

Blade is a Template Engine for Laravel. So try passing the value from the controller or you may define it in the routes.php for testing purposes. \n\n@include is used to include sub-views.",
2014-01-17T10:17:01
lukaserat :

I think you must understand the variable scope in Laravel Blade template. Including a template using @include will inherit all variables from its parent view(the view where it was defined). But I guess you can't use your defined variables in your child view at the parent scope. If you want your variable be available to the parent try use View::share($variableName, $variableValue) it will be available to all views as expected.",
2014-05-30T00:59:37
cecilozaur :

In this scenarion $myvar would be available only on the local scope of the include call.\n\nWhy don't you send the variable directly from the controller?",
2014-01-17T09:53:31
yy