在Laravel视图中使用名称空间 [英] Using namespace in laravel view
问题描述
如何在laravel View中使用命名空间?我的意思是我在 app/views
文件夹中有三个不同的文件夹 admin
, frontend
和 client
.
如果我要加载部分模板,请在 views/admin/account/profile中的
我必须像这样包含它: admin
部分 views/admin/partials/flush.blade.php
中说.blade.php
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')
我只想使用
@include('partials/flush')
我该怎么做?
推荐答案
您可以扩展刀片并编写适合您需求的函数.像这样:
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);
});
然后像描述的那样使用它,但使用 includeNamespaced
And then use it like you described but with includeNamespaced
@includeNamespaced('partials/flush')
如果愿意,也可以通过将其命名为 createMatcher('include')
If you want to you could also override @include
by naming it createMatcher('include')
注意您的" @includeNamespaced
/ @include
不能选择将参数传递给包含(第二个参数)的视图
Note "your" @includeNamespaced
/ @include
wont have the option to pass arguments to the view your including (second parameter)
一个小提示::当您更改 Blade :: extend
中的代码时,您必须删除 storage/views
中的缓存视图更改将显示在浏览器中.
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.
这篇关于在Laravel视图中使用名称空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!