hellosheikh
hellosheikh

Reputation: 3015

load a specific css and js files for a specific view page in Cakephp

I am working on Cakephp 2.x

Currently, I am managing my views is like this: I have a default.ctp file in my View/layout folder where all the reusable data is (for example menu, side bar, footer) and all the css and js files are also imported there. Then I have a view pages in my View/ControllerName/index.ctp file in which I am displaying the records.

Now what I want is to load specific css and js files for particular view page. How can I manage this?? Because at that time my all view pages is getting all the css and js files from the default.ctp file. But I want to load default.ctp layout as well but I want that if let's suppose I am calling a different view page then it select some css and js files from the default.ctp and skip the rest of files

Hope you understand what I am trying to do.

Upvotes: 0

Views: 2245

Answers (2)

Choma
Choma

Reputation: 708

This is a posible approach: In your beforeFilter function in AppController:

$this->set('loadXCss', false);
$this->set('loadYCss', false);
$this->set('loadZCss', false);

Then in any Controller, you should decide to show or not the css:

$this->set('loadZCss', true);

And last, in the layout:

<?php
echo this->Html->css('main.css', null, array('media' => 'screen,projection'));
if ( $loadXCss ) echo this->Html->css('x.css', null, array('media' => 'screen,projection'));
if ( $loadYCss ) echo this->Html->css('y.css', null, array('media' => 'screen,projection'));
if ( $loadZCss ) echo this->Html->css('z.css', null, array('media' => 'screen,projection'));
?>

Upvotes: 3

Derek
Derek

Reputation: 4751

In your AppController::beforeRender() function; add the following line:

$this->set('controller_name', $this->name);

In your default.ctp file, you can do an if or switch statement based on the $controller_name viewVar, and display some CSS/JS based on the value of it.

Or you can simply add overrides to other CSS and JS files and call those individually on each particular view you want to show.

Upvotes: 1

Related Questions