17

I am trying to include my plugins and custom js files in

frontend/views/layouts/main.php

So I used this code for js and css

<link rel="stylesheet" href="<?= Yii::$app->homeUrl; ?>chosen/chosen.css">
<script type="text/javascript" src="<?= Yii::$app->homeUrl; ?>js/jquery.fancybox.pack.js?v=2.1.5"></script>

but its not working. So what should I include to get my js and css files in view file?

Kartz
  • 533
  • 3
  • 8
  • 22

3 Answers3

12

If Your want to include script or css file in specific view you can use this :

$this->registerJsFile("/path/to/your/file/in/web/folder/script.js");

or

$this->registerCssFile("/path/to/your/file/in/web/folder/style.css");
AliLotfi
  • 432
  • 3
  • 14
  • 1
    thanks. You can use alias in your path, example: ```$this->registerJsFile(Yii::getAlias('@web') . '/js/custom.js');``` – m50 Aug 11 '21 at 15:36
11

For JS:

<?php 
 $script = <<< JS
   // Js Code Here 
 JS;
 $this->registerJs($script);

For CSS:

<?php $style= <<< CSS

   // CSS code here 

 CSS;
 $this->registerCss($style);
?>

This works fine.

Naeem Marzu
  • 186
  • 2
  • 14
8

Including it like you mentioned is not welcomed and definetely not "Yii style".

There are couple of ways to do that:

1) Use asset bundles. It's not necessarily to place it in AppAsset bundle. By default it's common bundle and included in main layout so all included assets will be published in every view.

You can create your own AssetBundle.

Note that for external assets (that are outside web accessible directory) you need to use sourcePath, otherwise - basePath and baseUrl properties.

With both options all you have to do in common case - fill $js and $css arrays and $depends for setting dependencies if it's needed.

You can read more by the link below.

2) Use registerCssFile() and registerJsFile().

First approach is preferable and recommended in official docs. It gives you dependencies handling and much more.

Official docs:

arogachev
  • 33,150
  • 7
  • 114
  • 117
  • When i use this code, the js script is showing in the view file, but its showing url not found "site.loc/frontend/web/js/classie.js" and at the same time files in the css folder working fine.. How to rectify js file 404 error? – Kartz Jun 04 '15 at 05:58
  • That simply means you specified wrong path and file not exist here. – arogachev Jun 04 '15 at 06:36