Eme*_*bah 78
选项1:
您可以这样使用view::share()
:
<?php namespace App\Http\Controllers;
use View;
//You can create a BaseController:
class BaseController extends Controller {
public $variable1 = "I am Data";
public function __construct() {
$variable2 = "I am Data 2";
View::share ( 'variable1', $this->variable1 );
View::share ( 'variable2', $variable2 );
View::share ( 'variable3', 'I am Data 3' );
View::share ( 'variable4', ['name'=>'Franky','address'=>'Mars'] );
}
}
class HomeController extends BaseController {
//if you have a constructor in other controllers you need call constructor of parent controller (i.e. BaseController) like so:
public function __construct(){
parent::__construct();
}
public function Index(){
//All variable will be available in views
return view('home');
}
}
Run Code Online (Sandbox Code Playgroud)
选项2: 使用作曲家:
app\Composers\HomeComposer.php
注意:app\Composers
如果不存在则创建
<?php namespace App\Composers;
class HomeComposer
{
public function compose($view)
{
//Add your variables
$view->with('variable1', 'I am Data')
->with('variable2', 'I am Data 2');
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以通过执行此操作将作曲家附加到任何视图
<?php namespace App\Http\Controllers;
use View;
class HomeController extends Controller{
public function __construct(){
View::composers([
'App\Composers\HomeComposer' => ['home'] //attaches HomeComposer to home.blade.php
]);
}
public function Index(){
return view('home');
}
}
Run Code Online (Sandbox Code Playgroud)
小智 30
将新的服务提供者添加到配置文件(config/app.php).
在新服务提供商的引导方法中使用:
View::share( 'something_cool', 'this is a cool shared variable' );
Run Code Online (Sandbox Code Playgroud)
现在您已准备好在所有视图中使用$ something_cool.
希望这可以帮助.
sha*_*a-1 12
正在寻找相同问题的解决方案,并在Laravel文档中找到了最佳解决方案.只要使用View::share
的AppServiceProvider
是这样的:
View::share('key', 'value');
Run Code Online (Sandbox Code Playgroud)
细节在这里.
Arj*_*ten 10
您可以使用视图作曲家执行此操作.加载模板时会执行视图编辑器.您可以为该视图传递具有附加功能的Closure.使用视图编辑器,您可以使用通配符.要为每个视图创建一个视图编辑器,只需使用a *
.
View::composer('*', function($view)
{
$view->with('variable','Test value');
});
Run Code Online (Sandbox Code Playgroud)
您也可以在没有闭包的情况下执行此操作,如文档中所示.
View::composer('*', 'App\Http\ViewComposers\ProfileComposer');
Run Code Online (Sandbox Code Playgroud)
配置文件编写器类必须具有compose方法.
渲染视图时执行视图编辑器.Laravel也观看了创作者.这些是在实例化视图时执行的.
您还可以选择使用BaseController
setupLayout方法.然后,您将加载的每个视图都通过setupLayout方法加载,该方法会添加一些额外的数据.但是,通过使用视图编辑器,您可以确定代码是否已执行.但是使用BaseController方法,您可以更加灵活,因为您可以跳过额外数据的加载.
编辑:如Nic Gutierrez所述,您也可以使用视图共享.
归档时间: |
|
查看次数: |
65028 次 |
最近记录: |