条件AppAssets

Jon*_*nny 6 php yii2

我有一个视图,我需要在我的标题中调用JQuery以及另一个JS库.对于所有其他页面,可以在文档末尾呈现它们.在Yii2中实现这一目标的最佳方法是什么?

目前我只是在我的AppAsset.php中这样做

public $js = [
  'https://code.highcharts.com/highcharts.js',
];
public $jsOptions = ['position' => \yii\web\View::POS_HEAD]; 
Run Code Online (Sandbox Code Playgroud)

我已经看过制作一个新的资产,但它似乎没有用,我不确定这是否是正确的方法.因为我不想在每个页面中首先渲染JS.

<?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
    ]
];
}
Run Code Online (Sandbox Code Playgroud)

Dee*_*ele 1

如果您查看AssetBundle::register(),您会发现它使用不带第二个参数的View::registerAssetBundle()。但第二个参数正是您需要的:

@param integer|null $position 如果设置,这会强制 javascript 文件的最小位置。这将根据资产 JavaScript 文件位置进行调整,如果无法满足要求,则会失败。如果为空,则资源包位置设置将不会更改。有关 javascript 位置的更多详细信息,请参阅 registerJsFile。

在您看来,在您注册资产包的地方,更改

EarlyJavaScriptAsset::register($this);
Run Code Online (Sandbox Code Playgroud)

$this->registerAssetBundle(EarlyJavaScriptAsset::className(), $this::POS_HEAD);
Run Code Online (Sandbox Code Playgroud)

$this->registerAssetBundle(EarlyJavaScriptAsset::className(), $this::POS_END);
Run Code Online (Sandbox Code Playgroud)

在第二个视图中

PS:当然$this是你的上下文View