简体   繁体   中英

Adding jQuery script to a single view in Yii2

I am working on the basic template of Yii2. I have got a jQuery script views/usuario/js/create.js that it's only going to be used in one view views/usuario/create.php .

I'd prefer not to use ...

public $jsOptions = array(
    'position' => \yii\web\View::POS_HEAD
);

... in assets/AppAsset.php in order to mantain loading of scripts at the end of the page.

create.js it's only needed in the create.php view so I'd prefer to load it just for the create.php view.

So I've tried unsuccessfuly to follow ippi's instructions Firebug keeps throwing me this error:

SyntaxError: expected expression, got '<'
http://www.example.com/usuario/js/create.js
Line 1

I guess there could be a problem with the route param of ...

$this->registerJsFile('js/create.js');

... but I can't find it out.

Any help would be appreciated.

registerJsFile() needs an url, you should simply publish (make it web accessible) your file before registering it, eg :

$pub = Yii::$app->assetManager->publish(__DIR__ . '/create.js');
$this->registerJsFile($pub[1], ['depends' => ['yii\web\JqueryAsset']]);

Or you could create an asset bundle and registering it in your view.

Read more about publish() and registerJsFile() .

尝试使用$this->registerScriptFile('views/usuario/js/create.js');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM