问题
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