我想知道在我的主刀片模板中动态包含js文件的好方法是什么
<?php
$currentRoute = Route::currentRouteName();
$currentRoute = $currentRoute?$currentRoute:'home';
$currentRoute = explode('.',$currentRoute);
?>
<script src="{{$currentRoute[0]}}.js"></script>
Run Code Online (Sandbox Code Playgroud)
但只是不那么棘手:)
那段时间我做过类似的事情.在这里,我的"技巧"是这样做的.
首先,您需要一个顶级控制器类
class MainController extends Controller {
protected static $js_files = [];
protected static $css_files = [];
public static function boot()
{
view()->share('js_files', static::$js_files);
view()->share('css_files', static::$css_files);
parent::boot();
}
}
Run Code Online (Sandbox Code Playgroud)
然后,所有控制器必须从MainController类继承.
我使用关键字"static ::"而不是"self ::"的原因是因为我想要检索最新的子属性而不是"MainController"属性,它会给我关键字"self ::".
请参阅http://php.net/manual/en/language.oop5.late-static-bindings.php 在刀片布局中,在head部分中执行以下操作:
@foreach($css_files as $src)
<link href="{{$src}}" rel="stylesheet">
@endforeach
Run Code Online (Sandbox Code Playgroud)
在结束身体标记之前
@foreach($js_files as $src)
<script src="{{$src}}"></script>
@endforeach
Run Code Online (Sandbox Code Playgroud)
在每个控制器中,您必须在$ js_files和$ css_files继承的属性中放入所有js/css的源代码.
如果要仅为一个路径包含JS/CSS,可以直接在方法中添加文件源.
瞧!
| 归档时间: |
|
| 查看次数: |
1581 次 |
| 最近记录: |