Home  >  Article  >  PHP Framework  >  How to introduce js files in yii2

How to introduce js files in yii2

王林
王林Original
2020-02-19 10:58:593062browse

How to introduce js files in yii2

Question:

For example, I create css files and js files in the web folder, and create resource controllers in assets. So how do I call the web/css/test.css or web/js/test/js file when I am in the view layer?

The method is as follows:

1. Module reference (all pages of this module will reference it)

Yii2 uses the AssetBundle resource package class for CSS/JS management.

(Recommended tutorial: yii framework)

(Note: YII2 basic version assets/AppAsset.php, YII2 advanced version frontend/assets/AppAsset.php, here Take the basic version as an example)

namespace app\assets;
use yii\web\AssetBundle;
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class AppAsset extends AssetBundle
{
    public $basePath = &#39;@webroot&#39;;
    public $baseUrl = &#39;@web&#39;;
    //全局css 在这个添加css文件
    public $css = [
        &#39;css/site.css&#39;,
        &#39;css/test.css&#39;,
    ];
    //全局js  在这里添加js文件
    public $js = [
        &#39;js/test.js&#39;,
    ];
    //依赖关系
    public $depends = [
        &#39;yii\web\YiiAsset&#39;,
        &#39;yii\bootstrap\BootstrapAsset&#39;,
    ];
}

2. To reference

in a view file, you only need to add the following code in the view file.

//引用css文件,注意自己的文件路径
<?php $this->registerCssFile(&#39;css/test.css&#39;);?>
//引用js文件,注意自己的文件路径<span class="redactor-invisible-space"></span>
<?php $this->registerJsFile(&#39;js/test.js&#39;);?>

If you want to learn more programming related content, please pay attention to the Programming Introduction column on the php Chinese website!

The above is the detailed content of How to introduce js files in yii2. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:yii2 running processNext article:yii2 running process