Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional AppAssets

Tags:

php

yii2

I have one view in which I need to call JQuery in my header along with another JS Library. For all other pages they can be rendered at the end of the document. What's the best way to achieve this in Yii2?

Currently I am just doing this in my AppAsset.php

public $js = [
  'https://code.highcharts.com/highcharts.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD]; 

I have looked at making a new Asset, but it didn't seem to work and I wasn't sure if it was the right way to go about it. As I don't want to render the JS first in every page.

<?php

namespace app\assets;

use yii\web\AssetBundle;

class EarlyJavaScriptAsset extends AssetBundle
{
public $js = [
'https://code.highcharts.com/highcharts.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD]; 

public $publishOptions = [
    'only' => [
        'report/report-1', // this is view folder location
    ]
];
}
like image 344
Jonnny Avatar asked Jan 19 '16 15:01

Jonnny


1 Answers

If you would look at AssetBundle::register() you would see that it uses View::registerAssetBundle() without second parameter. But that second parameter is the thing you need:

@param integer|null $position if set, this forces a minimum position for javascript files. This will adjust depending assets javascript file position or fail if requirement can not be met. If this is null, asset bundles position settings will not be changed. See registerJsFile for more details on javascript position.

In your view, where you register your asset bundle, change

EarlyJavaScriptAsset::register($this);

to

$this->registerAssetBundle(EarlyJavaScriptAsset::className(), $this::POS_HEAD);

and

$this->registerAssetBundle(EarlyJavaScriptAsset::className(), $this::POS_END);

in second view

PS: Of course $this is context of your View.

like image 108
Deele Avatar answered Oct 01 '22 23:10

Deele