I
I
Igor Vasiliev2018-05-21 15:44:17
Yii
Igor Vasiliev, 2018-05-21 15:44:17

How to write attributes into javascript assets in Yii2?

Hello.
--
There is an asset for the layout, it needs attributes:

<script src="vendor/pace.js/pace.js" data-pace-options='{ "target": ".content-wrap", "ghostTime": 1000 }'></script>
<script id="test" src="vendor/underscore/underscore.js"></script>

How to add them here?
<?php

namespace frontend\assets;

use yii\web\AssetBundle;

/**
 * Main frontend application asset bundle.
 */
class AppAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/application.min.css',
    ];
    public $js = [
        'js/defina.min.js', // нужно добавить id и data-...
    ];
    public $depends = [
        'yii\web\YiiAsset',
        'yii\bootstrap\BootstrapAsset',
    ];
}

Who faced it?
In WordPress , this task is performed by a function like:
...
function wpb_adding_scripts() {
    wp_register_script('script-defina', get_template_directory_uri() . '/js/defina.min.js','','1.1', true);    
    wp_enqueue_script('script-defina');    
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );
...

So there is something similar on Yii2, or should I add the function myself?
Something like:
...
    public function init()
    {
        if (\yii::$app->request->url == '/video') {
            $this->js[] = 'js/jquery.countdown.js', ['id' => 'test', 'data-pace-options' => '{ "target": ".content-wrap", "ghostTime": 1000 }'];
            $this->js[] = 'js/script.time.js';
        }
    }
...

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Timofeev, 2018-05-21
@Isolution666

https://www.yiiframework.com/doc/api/2.0/yii-web-a...

public $js = [
        'js/defina.min.js' => ['data-pace-options'=>'{ "target": ".content-wrap", "ghostTime": 1000 }']
    ];

I don’t remember for sure, the nesting may be different, try

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question