Home > Article > PHP Framework > How to import css and js files into yii2
There are many ways to introduce it:
1. You can introduce it directly on the view page
<?php use yii\helpers\Html;?><?=Html::cssFile('@web/css/index.css')?><?=Html::jsFile('@web/js/jquery.min.js')?>
2 , you can directly write native code to import, the path is the project directory /web/css or /js
<script src="js/nav.js"></script>
3, you can use assetBundle to manage css styles and js scripts
Resource package definition: basic/assets/AppAsset.php
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace app\assets; use yii\web\AssetBundle; /** * @author Qiang Xue <qiang.xue@gmail.com> * @since 2.0 */ class AppAsset extends AssetBundle{ public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = [ 'css/site.css', 'css/base.css' ]; public $js = [ 'js/sliders.js' ]; public $depends = [ //依赖包,没有可以不写 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; //定义按需加载JS方法,注意加载顺序在最后 public static function addScript($view, $jsfile) { $view->registerJsFile($jsfile, [AppAsset::className(), 'depends' => 'api\assets\AppAsset']); } //定义按需加载css方法,注意加载顺序在最后 public static function addCss($view, $cssfile) { $view->registerCssFile($cssfile, [AppAsset::className(), 'depends' => 'api\assets\AppAsset']); } }
Write at the beginning of the view file:
<?php use yii\helpers\Html;use app\assets\AppAsset; AppAsset::register($this); ?>
Up to now, we can test on the browser and find that it is not introduced css and js files, we need to pay attention here, we still need the last step:
We need to add some code to the view file (note: if we use the public view file, we can add it to the public view file, if not Use, can be placed in a separate page)
<?php$this->beginPage() ?> <?php $this->head() ?> <?php $this->beginBody() ?> <?php $this->endBody() ?> <?php $this->endPage() ?>
4. There is no need to define the method in the resource package manager, just introduce it directly in the view page
AppAsset::register($this); //css定义一样 $this->registerCssFile('@web/css/font-awesome.min.css',['depends'=>['api\assets\AppAsset']]); $this->registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=>['api\assets\AppAsset']]); //$this->registerJsFile('@web/js/jquery-ui.custom.min.js',['depends'=>['api\assets\AppAsset'], 'position'=>$this::POS_HEAD]);
Recommended related article tutorials: yii tutorial
The above is the detailed content of How to import css and js files into yii2. For more information, please follow other related articles on the PHP Chinese website!