How to dynamically load css file for each action in a controller?

620 Views Asked by At

I have a controller named 'Student' with two actions called 'index' and 'add'. I want to load different css files for each of the action. So far i have tried is, i have imported Html Helper, created object of it and called its css method. When i run it, it is not throwing any error, nor showing expected result. Means, it is not loading css file dynamically in my view.. How can i dynamically load css files in different views from Controller?

Code:-

<?php

App::import('Helper','Html');

class StudentController extends AppController
{
    public function index()
    {
//        $current_controller = $this->params['controller'];
//        echo $current_controller;

        //$view=new  View(new Controller($current_controller));

        //$Html=new HtmlHelper($view);
        $Html=new HtmlHelper(new View(null));
        //$html=new HtmlHelper(new View());
        $Html->css('cake.generics');

        //echo ;
        //$this->Html->css("cake.generics");
    }

    public function add()
    {
//        $current_controller = $this->params['controller'];
//        echo $current_controller;

        $html=new HtmlHelper(new View(null));
        $html->css("mystyle.css");

    }

}
3

There are 3 best solutions below

0
On BEST ANSWER

you can also create a global layout file in View > Element like default_assets.ctp

after that add this file in your default layout file like,default_layout.ctp in View > Layout folder

and after access this in your controller like

public function index(){
 $this->layout = "default_layout";
}
1
On

You can do it in view file e.g

//in your View/Students/add.ctp
$this->Html->css('yourstyle', array('block' => 'yourStyle'));

//in your layout file
echo $this->fetch('yourStyle');

the same with js files

// in your view
$this->Html->script('yourjs', array('block' => 'yourJs'));

//in your layout file
echo $this->fetch('yourJs');
0
On

I got it working in this way,

I have added "mycss" variable in controller, index action:-

$this->set('mycss','custom');

And accessed this mycss variable from layout file:-

if(isset($mycss)){
    $this->Html->css("$mycss");
}

And it worked.