Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

yii2

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?

like image 342
Kartz Avatar asked May 29 '15 07:05

Kartz


People also ask

How to register css file in yii2?

Registering CSS files A CSS file can be registered using the following: $this->registerCssFile("@web/css/themes/black-and-white. css", [ 'depends' => [\yii\bootstrap\BootstrapAsset::class], 'media' => 'print', ], 'css-print-theme'); The above code will add a link to the /css/themes/black-and-white.

What is more appropriate way to include JavaScript as an external file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.


2 Answers

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");
like image 171
AliLotfi Avatar answered Oct 18 '22 11:10

AliLotfi


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.

like image 38
Naeem Marzu Avatar answered Oct 18 '22 09:10

Naeem Marzu