Using namespace in laravel view

走远了吗. 提交于 2021-02-11 06:20:18

问题


How to use namespace in laravel View? I mean I have three different folders admin, frontend and client in app/views folder.
If I want to load a partial template lets say from admin section views/admin/partials/flush.blade.php in views/admin/account/profile.blade.php I have to include it like:

@include('admin/partials/flush')

instead I want to just use

@include('partials/flush')

How can i do that?


回答1:


You can extend blade and write a function that fits your needs. Like this:

Blade::extend(function($view, $compiler)
{
    $pattern = $compiler->createMatcher('includeNamespaced');

    $viewPath = realpath($compiler->getPath());
    $parts = explode(DIRECTORY_SEPARATOR, $viewPath);
    $viewsDirectoryIndex = array_search('views', $parts);
    $namespace = $parts[$viewsDirectoryIndex + 1];

    $php = '$1<?php ';
    $php .= 'if($__env->exists(\''.$namespace.'.\'.$2)){';
    $php .= 'echo $__env->make(\''.$namespace.'.\'.$2)->render();';
    $php .= '}';
    $php .= 'else {';
    $php .= 'echo $__env->make($2)->render();';
    $php .= '}';
    $php .= '?>';

    return preg_replace($pattern, $php, $view);
});

And then use it like you described but with includeNamespaced

@includeNamespaced('partials/flush')

If you want to you could also override @include by naming it createMatcher('include')

Note "your" @includeNamespaced / @include wont have the option to pass arguments to the view your including (second parameter)

A little tip: When you change the code inside Blade::extend you have to delete the cached views in storage/views for the changes to show up in your browser.



来源:https://stackoverflow.com/questions/27986317/using-namespace-in-laravel-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!