我正在尝试使用类似于以下(widget.blade.PHP)的Laravel刀片创建
HTML小部件:
@push('scripts') <script src="{{ asset('js/foo.js') }}"></script> <script> ... </script> @endpush @push('styles') <link href="{{ asset('css/bar.css') }}" rel="stylesheet"> @endpush <div> ... HTML contents </div>
我在其他刀片中使用小部件,如:
<div> ... @include('widget') </div> <div> ... @include('widget') </div>
问题是当我在页面中多次使用窗口小部件时,“脚本”和“样式”重复多次.
如何防止Laravel多次推送“脚本”和“样式”?
在下面的回答中,我假设您熟悉
Blade extension.此方法已在Laravel 5.2和5.3上进行了测试(请参阅下面的注释).
原文链接:https://www.f2er.com/laravel/137944.html在测试Ismail RBOUH’s Answer(所以请阅读它)之后,解决方案似乎有两个问题:
1- $isDisplayed变量与其他包含的小部件不在同一范围内,因此每个@include将其脚本推送到堆栈.结果我将其更改为:
Blade::directive('pushonce',function ($expression) { $isDisplayed = '__pushonce_'.trim(substr($expression,2,-2)); return "<?PHP if(!isset(\$__env->{$isDisplayed})): \$__env->{$isDisplayed} = true; \$__env->startPush{$expression}; ?>"; }); Blade::directive('endpushonce',function ($expression) { return '<?PHP $__env->stopPush(); endif; ?>'; });
2-解决方案将@pushonce的使用限制为一个小部件.即,在2个或更多小部件(widget1.blade.PHP,widget2.blade.PHP,…)的情况下,它阻止推送其他小部件脚本.所以,我使用以下代码将域添加到@pushonce:
Blade::directive('pushonce',function ($expression) { $domain = explode(':',trim(substr($expression,-2))); $push_name = $domain[0]; $push_sub = $domain[1]; $isDisplayed = '__pushonce_'.$push_name.'_'.$push_sub; return "<?PHP if(!isset(\$__env->{$isDisplayed})): \$__env->{$isDisplayed} = true; \$__env->startPush('{$push_name}'); ?>"; }); Blade::directive('endpushonce',function ($expression) { return '<?PHP $__env->stopPush(); endif; ?>'; });
用法:
widget1.blade.PHP
@pushonce('scripts:widget1') <script src="{{ asset('js/foo.js') }}"></script> <script> ... </script> @endpushonce
widget2.blade.PHP
@pushonce('scripts:widget2') <script src="{{ asset('js/bar.js') }}"></script> <script> ... </script> @endpushonce
L 5.3的注意事项:
更改以下行:
$domain = explode(':',-2)));
至
$domain = explode(':',1,-1)));