Home >PHP Framework >Laravel >Laravel assigns values to public templates
Many times during the development process, values are assigned to public templates, such as the top navigation bar, the bottom of the page, etc. It is impossible to assign values in every controller.
The solution in Laravel is as follows:
Modify
App\Providers\AppServiceProvider
Add
in the boot method View()->composer('common.header',function ($view){ //common.header corresponds to Blade template
});
You can also assign values to all templates
View()->share('key', 'value');
======================================
View composers are related to views. They are used in the boot() function of a service provider. When a view is loaded, due to the role of view composer, it calls a certain function and passes parameters.
1, create service provider
php artisan make:provider ComposerServiceProvider
Add ComposerServiceProvider to config In
2 in /app.php, write view composer
public function boot() { view()->composer( 'app', //模板名 'App\Http\ViewComposers\MovieComposer' //方法名或者类中的方法 ); }
which means that once app.blade.php is loaded, execute App\Http The
composer function in \ViewComposers\MovieComposer
(the composer function is executed here by default), if you want to change it, just
view()-> composer('app','App\Http\ViewComposers\MovieComposer<a href="https://my.oschina.net/u/862816" class="referer" target="_blank">@foobar</a>');
//Your own defined method
The foobar function is executed here
Write this <pre class="brush:php;toolbar:false"><?php
namespace App\Http\ViewComposers;
use Illuminate\View\View;//**记得引入这个啊(因为在composer函数参数里使用了View类)**
class MovieComposer
{
public $movieList = [];
public function __construct()
{
$this->movieList = [
'Shawshank redemption',
'Forrest Gump',
];
}
public function compose(View $view)
{
$view->with('latestMovie');
}
}</pre>
App\Http\ViewComposers\MovieComposer.php, and other
All templates must use *regular expression
view()->composer('*', function (View $view) { //logic goes here });
If you want to specify multiple views to use, wrap them in an array
view()->composer(['nav', 'footer'],'App\Http\ViewComposers\MovieComposer'); 或者 view()->composer(['admin.admin'], function ($view){ $column = $this->object_array(DB::table('column')->get()); foreach($column as $k=>$v){ $chid = explode(',',$v['childid']); foreach($chid as $value){ $column[$k]['chname'][] = $this->object_array(DB::table('column_child')->where('id',$value)->first()); } } $view->with('columns',$column); });
More PHP related technologies Article, please visit the PHP Tutorial column to learn!
The above is the detailed content of Laravel assigns values to public templates. For more information, please follow other related articles on the PHP Chinese website!