我遇到了一个问题,我不想在某些 View 中显示 X 元素。
真实的例子是我不想在contact
和about us
页面上显示产品图片 slider ,但它应该在所有其他页面上可见(about还有 6 个)
那么如何在 n of m 页面中排除呈现 div 而无需制作很长的 @if
条件?
对时尚的解决方案有什么想法吗?
编辑
回答为什么我不想把它放在独立 View 文件中的问题:
想象一下,您希望这条线在您的所有 View 中都可见,除了特定的一个,而且只有一个
<span>Lorem Ipsum</span>
这只是一行 HTML 代码,不值得在项目中创建另一个文件,因为它会使项目文件树变得一团糟,另一个示例是一个糟糕的解决方法
@if(\Request::route()->getName() !== "some.very.long.route.alias.name.that.looks.ugly")
<span>Lorem Ipsum</span>
@endif
当项目增长时使代码难以阅读和理解
编辑 2
我预测了一些建议的解决方案并且已经写了为什么这不是处理这个问题的合适方法。我正在寻找一种类似于 @can
或 @cannot
的解决方案,这取决于当前路线
编辑 3: 研究解决方案
编辑 4: 我在这里发布了一个答案,但它还不完美(我不会将其标记为已接受),所以为了这个主题的读者,我将在下面粘贴它的副本
Ok I have made a simple blade directive that solves this case in a well-looking way
At first, create an array that determines route access for html snippet
Best place would be to create this file in config directory, on example apresence.php
file<?php return [ 'ipsum' => [ // presence alias 'about', // disallowed route #1 'contact' // disallowed route #2 ], ];
Then create a directive in
AppServiceProvider.php
class<?php namespace App\Providers; use Illuminate\Support\Facades\Blade; use Illuminate\Support\ServiceProvider; class AppServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { Blade::directive('presence', function($alias) { return "<?php if (in_array(\Request::route()->getName(),config('presence.'.$alias))):?>"; }); Blade::directive('endpresence', function() { return '<?php endif; ?>'; }); } /** * Register any application services. * * @return void */ public function register() { // } }
And in the final usage of this trick in html view
@presence('ipsum') <span>Lorem Ipsum</span> @endpresence
It will print
Lorem Ipsum
if the current route name is not inipsum
array (which is declared in\App\config\presence.php
file so we can access it withconfig()
helper method)It would be great if I could handle wildcard characters, like
<?php return [ 'ipsum' => [ // presence alias 'admin.category.*', // advanced route pattern #1 'admin.users.*' // advanced route pattern #2 ], ];
But I will look into it later.
Feedback, or criticism is always welcome :)
最佳答案
如果 contact
和 about us
有它们自己的 URI,您可以尝试匹配它以确定是否应该显示 not... 的元素
if (!\Request::is('contact') && !\Request::is('about-us')) {
// Show element X
}
或者另一种方法是添加一个设置一些变量的中间件,例如 $dontShowElement
并设置一个 View 编辑器并将该变量传递给所有 View 。然后,您需要做的就是在输出元素之前检查该变量是否存在,并且只提供您希望将该元素隐藏在该中间件上的那 2 条路由。
关于php - 在 Laravel 5.3 的任何 View 中隐藏任何元素的聪明方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40117056/