Unable to register css / js using assets / registerCss function

1.6k views Asked by At

I had created a testasset.php as follows :

<?php

namespace app\assets;
use yii\web\AssetBundle;

class TestAsset extends AssetBundle {
    /*public $basePath = '@webroot';
      public $baseUrl = '@web'; */
      public $sourcePath = '@app/assets';
      public $css = [
        '/css/test.css',
      ];
      public $js = [];
      public $depends = [
      /*  'yii\web\YiiAsset',
          'yii\bootstrap\BootstrapAsset', */
      ];
}

In controller i am simply rendering view file which register above asset.

view :

<?php 

use app\assets\TestAsset;
TestAsset::register($this);
$this->beginPage(); ?>

<html>
  <head>
    <title>Register JS and CSS</title> <?php 
     //Yii::$app->view->registerCssFile('/css/style.css');?>
    <!-- <link rel="stylesheet" href="/css/test.css" type="text/css" /> -->
  </head>
  <body>
    <div id="page">
      <div id="logo">
        <h1><a href="/" id="logoLink">Register JS and CSS Test</a></h1>
      </div>
      <div id="nav">
        <ul>
          <li><a href="#">!</a></li>
          <li><a href="#">@</a></li>
          <li><a href="#">#</a></li>
        </ul>
      </div>
      <div id="content">
        <h2>Test</h2>
        <p> XYZ...!!! </p>
        <p> ABC...!!! </p>
      </div>
      <div id="footer"> 
        <p> Webpage made by <a href="/" target="_blank">XYZ</a> </p>
      </div>
    </div>
  </body>
</html>

But my test.css file is not getting registered. I had tried using basepath and baseurl as well and registerCss Yii2 function but with no success.

Anyone Please suggest where i am lacking in my code.

3

There are 3 answers

5
Bizley On BEST ANSWER

You need to add

<?php $this->head() ?>

preferably somewhere between <head> and </head> for the header asset files to be rendered.

1
Yasar Arafath On

Simply add this in view file

<?php 
   $this->registerCssFile('PATH_TO_FILE');
?>
0
Taras On

I have had the same issue on one of my advanced application template projects. I've compared my layout/main.php file with the same on the Yii2 advanced application template and found missing $this->endPage() at the end of file. It was removed by mistake and without it no js, ccs assets worked.