Yii2 - Enable JS Script For a Specific View

I want to include my js script specific.js for a specific view with the action identifier specific-action-id . I do not want specific.js included in every page.

To enable js script for the whole site, I usually need to edit AppAsset.php . To this end, what should I do?

+8
yii2
source share
3 answers

You should just register this js file in your view, for example.

 $this->registerJsFile('@web/js/specific.js'); 

More details: http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html#registering-scripts

+14
source share

@soju is right. But you can also create specific asset packages for using certain types. Your specific js files may be a group of files in this situation, you can use asset packages and you can use any kinds that you want.

+1
source share

It is strongly recommended that you use asset packages to register external JS files, rather than registerJsFile (), as they provide better flexibility and more detailed dependency configuration. In addition, using asset bundles allows you to combine and compress multiple JS files, which is desirable for sites with high traffic.

So, you can create a new AppAsset file and put your css and javascript files in it.

Create Asset Bundle Package

In the \ assets directory, we create StatusAsset.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 StatusAsset extends AssetBundle { public $basePath = '@webroot'; public $baseUrl = '@web'; public $css = []; public $js = [ '/js/jquery.simplyCountable.js', '/js/twitter-text.js', '/js/twitter_count.js', '/js/status-counter.js', ]; public $depends = [ 'yii\web\YiiAsset', 'yii\bootstrap\BootstrapAsset', ]; } 

In your view file

 use app\assets\StatusAsset; StatusAsset::register($this); 

Resources http://www.yiiframework.com/doc-2.0/guide-output-client-scripts.html https://code.tutsplus.com/tutorials/how-to-program-with-yii2-working-with- asset-bundles - cms-23226

+1
source share

All Articles