如何在 yii2 中添加 assetbundle js/css 仅在一页中添加?
How to add assetbundle js/css add only in one page in yii2?
我在 vendor/bower 文件夹中添加了完整日历 js/css。我想将其添加到一页中。
我阅读了关于此的 abt AssestBundle link - http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
但是这会添加到所有页面中。
在 Yii 2 框架资产包中推荐使用 js / css。它不仅限于仅添加到所有页面。您只能在特定视图中使用它。
JsTree
插件的资产包示例:
<?php
namespace backend\assets;
use yii\web\AssetBundle;
class JsTreeAsset extends AssetBundle
{
public $sourcePath = '@bower_components/jstree/dist';
public $js = [
'jstree.min.js',
];
public $css = [
'themes/default/style.min.css',
];
public $depends = [
'yii\web\JqueryAsset',
];
}
在此示例中,使用了 @bower_components
别名,为了使其正常工作,您还需要在应用程序 bootstrap 文件中注册它(在高级应用程序模板中,此文件为 common/config/bootstrap.php
):
Yii::setAlias('bower_components', dirname(dirname(__DIR__)) . '/bower_components');
然后在视图中需要使用的地方,调用这个asset bundle的register()
方法,传入当前视图:
use backend\assets\JsTreeAsset;
...
JsTreeAsset::register($this);
应用程序模板中包含的默认资产包 (AppAsset
) 中的文件会加载到每个视图中,因为它已在应用程序布局中注册并且布局应用于所有视图。
我在 vendor/bower 文件夹中添加了完整日历 js/css。我想将其添加到一页中。
我阅读了关于此的 abt AssestBundle link - http://www.yiiframework.com/doc-2.0/guide-structure-assets.html
但是这会添加到所有页面中。
在 Yii 2 框架资产包中推荐使用 js / css。它不仅限于仅添加到所有页面。您只能在特定视图中使用它。
JsTree
插件的资产包示例:
<?php
namespace backend\assets;
use yii\web\AssetBundle;
class JsTreeAsset extends AssetBundle
{
public $sourcePath = '@bower_components/jstree/dist';
public $js = [
'jstree.min.js',
];
public $css = [
'themes/default/style.min.css',
];
public $depends = [
'yii\web\JqueryAsset',
];
}
在此示例中,使用了 @bower_components
别名,为了使其正常工作,您还需要在应用程序 bootstrap 文件中注册它(在高级应用程序模板中,此文件为 common/config/bootstrap.php
):
Yii::setAlias('bower_components', dirname(dirname(__DIR__)) . '/bower_components');
然后在视图中需要使用的地方,调用这个asset bundle的register()
方法,传入当前视图:
use backend\assets\JsTreeAsset;
...
JsTreeAsset::register($this);
应用程序模板中包含的默认资产包 (AppAsset
) 中的文件会加载到每个视图中,因为它已在应用程序布局中注册并且布局应用于所有视图。