Summary of Laravel Assigning Values to Common Templates
- 2021-12-12 08:03:44
- OfStack
Many times in the development process, common templates are assigned values, such as the top navigation bar, the bottom of the page, etc. It is impossible to assign values once 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 Correspondence Blade Template $view->with('key', 'value'); });
You can also assign values to all templates
View()->share('key', 'value');
view composers is related to views, and is used in the boot () function of an service provider, that is, when an view is loaded, due to the role of view composer, it calls a certain function to pass a parameter or something.
1. Create service provider
php artisan make:provider ComposerServiceProvider
Add ComposerServiceProvider to
config/app.php
Inside
2. Write view composer
public function boot() { view()->composer( 'app', // Template name 'App\Http\ViewComposers\MovieComposer' // Method name or method in class ); }
It means that once app. blade. php is loaded, it is executed
App\Http\ViewComposers\MovieComposer
In
composer
Function (the reason why composer function is executed here is the default), if you want to change one, just
view()->composer('app','App\Http\ViewComposers\MovieComposer@foobar');
//Self-defined method
The foobar function is executed here
In
App\Http\ViewComposers\MovieComposer.php
It says so in the book
<?phpnamespace App\Http\ViewComposers;use Illuminate\View\View;//** Remember to introduce this (because in composer Function parameter uses the View Class) **class MovieComposer{ public $movieList = []; public function __construct() { $this->movieList = [ 'Shawshank redemption', 'Forrest Gump', ]; } public function compose(View $view) { $view->with('latestMovie'); }}
3. When all templates are needed, use * regular expressions
view()->composer('*', function (View $view) { //logic goes here});
To specify multiple view uses, wrap them in an array
view()->composer(['nav', 'footer'],'App\Http\ViewComposers\MovieComposer'); Or 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); });