ahm*_*med 11 php laravel blade laravel-5
在Laravel 5中我需要在编译之前修改视图内容,方法是添加以下字符串:"@ extends(foo)"
注意:更改视图文件内容不是一个选项
所以这个过程就像是(每次调用一个视图)
我试过使用viewcomposer和中间件没有运气
这是我的作曲家服务提供者:
namespace App\Providers;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
public function boot()
{
View::composer('pages/*', function ($view) {
// i want to do the following:
// 1- find all view under directory resources/views/pages
// 2- then add the following blade command "@extends(foo)" at the beginning of the view before compile
});
}
public function register()
{
//
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的视图中间件尝试(在中间件我能够修改编译后的视图内容:()
<?php
namespace App\Http\Middleware;
use Closure;
class ViewMiddleware
{
public function handle($request, Closure $next)
{
$response = $next($request);
if (!method_exists($response,'content')) {
return $response;
}
$content = "@extends('layouts.app')".$response->content();
$response->setContent($content);
return $response;
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢
更新:我需要完成的是基于其父目录扩展具有布局的视图
例如,我的视图目录具有以下结构
我需要视图"controlpanel.blade.php"来布局"layout/admin.blade.php",因为它的父文件夹名为"admin"
-view
|--pages
|--admin
|--controlpanel.blade.php
|--layouts
|--admin.blade.php
Run Code Online (Sandbox Code Playgroud)
如果你想“动态”扩展视图,这里有一种方法:
$view = 'foo'; // view to be extended
$template = view('home')->nest('variable_name', $view, ['data' => $data]);
return $template->render();
Run Code Online (Sandbox Code Playgroud)
而在你看来:
@if (isset($variable_name))
{!! $variable_name !!}
@endif
Run Code Online (Sandbox Code Playgroud)
这在 Laravel 5.2 中对我有用。
我仍然认为组织视图并让它们扩展相应的布局而不是动态传递更容易。
编辑:
这是另一种方法。但没有检查Laravel的最新版本。
在您看来:
@extends($view)
并在控制器中:
$view = 'foo';
return view('someview', compact('view'));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2880 次 |
| 最近记录: |