Kartz
Kartz

Reputation: 533

Yii2 - How to include external js and css in view file

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?

Upvotes: 17

Views: 44708

Answers (3)

Naeem Marzu
Naeem Marzu

Reputation: 186

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.

Upvotes: 11

AliLotfi
AliLotfi

Reputation: 430

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");

Upvotes: 12

arogachev
arogachev

Reputation: 33548

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:

Upvotes: 8

Related Questions