Ish
Ish

Reputation: 2105

How to add assetbundle js/css add only in one page in yii2?

I have added fullcalendar js/css in vendor/bower folder. I want to add this into just one page.

I read abt AssestBundle on this link - http://www.yiiframework.com/doc-2.0/guide-structure-assets.html

But this add in all the pages.

Upvotes: 2

Views: 1031

Answers (1)

arogachev
arogachev

Reputation: 33538

In Yii 2 framework asset bundles is recommended way of working with js / css. It's not limited to just adding to all pages. You can use it only in specific view.

Example of asset bundle for JsTree plugin:

<?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',
    ];
}

In this example, @bower_components alias is used, in order to get it working you also need to register it in application bootstrap file (in advanced application template this file is common/config/bootstrap.php):

Yii::setAlias('bower_components', dirname(dirname(__DIR__)) . '/bower_components');

Then, in view where you need to use it, call register() method of this asset bundle and pass current view:

use backend\assets\JsTreeAsset;

...

JsTreeAsset::register($this);

The files in default asset bundle (AppAsset) which included in application templates are loaded in every view because it's registered in application layout and layout is applied to all views.

Upvotes: 3

Related Questions