Laravel 5.x覆盖特定用户的视图

问题描述 投票:0回答:1

我试图根据登录用户theme覆盖视图。我们有一个themes表,每个用户都有一个QK到theme

我的目录结构如下:

- resources
  - themes 
    - my_custom_theme
  - views

我已经创建了自己的ViewServiceProvider副本,并且正在扩展原始版本。这工作正常,我压倒registerViewFinder(),这也很好。然而,在应用程序周期的这个阶段,auth()->user()没有设置,所以我无法得到他们的主题。

    /**
     * Register the view finder implementation.
     *
     * @return void
     */
    public function registerViewFinder()
    {
        $this->app->bind('view.finder', function ($app) {

            //dd($app['config']['view.paths']);

            //dd(auth()->user()->theme);

            return new FileViewFinder($app['files'], $app['config']['view.paths']);
        });
    }

我想基于登录用户主题生成路径,因此可以从此目录加载。 resources/themes/my_custom_theme

如果我在这里无法访问该用户,那么预期的方法是什么?

非常感谢

php laravel laravel-5 laravel-blade templating
1个回答
0
投票

我能够通过使用Route Middleware覆盖视图来实现这一目标。在此之前的任何事情都无法访问Auth::user()

<?php
namespace App\Http\Middleware;

use Illuminate\View\FileViewFinder;

class SwitchTheme
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request, \Closure $next, $guard = null)
    {
        if (auth()->check()) {
            $paths = \Config::get('view.paths');
            $base = resource_path('themes');
            $theme = auth()->user()->theme;

            // add custom view path to the top of the path stack
            array_unshift($paths, "$base/$theme");

            // create a new instance of the Laravel FileViewFinder and set.
            $finder = new FileViewFinder(app()['files'], $paths);
            app()['view']->setFinder($finder);
        }

        return $next($request);
    }
}

我获取现有的视图路径数组,并从数据库中检索用户主题。卸下新路径,在我的情况下是resource_path/theme_name

我找不到重置路径的方法,使用$finder->addLocation会将你的主题路径放在堆栈的底部,这样它就不会覆盖。在这种情况下,我需要创建一个新的FileViewFinder实例,为它提供新的路径数组,然后覆盖app()['view']上的现有finder。

好又简单,只需一个中间件。

要加载,只需将\App\Http\Middleware\SwitchTheme::class添加到$middlewareGroups中的Kernel.php数组

© www.soinside.com 2019 - 2024. All rights reserved.