jump to navigation

Override CSS for an specific action February 11, 2006

Posted by rossoft in CakePHP.
trackback

Sometimes I have a view that I need to override CSS and I can’t change the .thtml (because I do something like scaffolding). So I have done a little snippet code for doing this.

If exists any of these files, then it will be referenced automatically by a link stylesheet tag:

  • /app/webroot/{controller_name}/css.css
  • /app/webroot/{controller_name}/ie.css ( referenced only for ie <=6)
  • /app/webroot/{controller_name}/{action_name}.css
  • /app/webroot/{controller_name}/{action_name}_ie.css ( referenced only for ie <=6)

Put this code snippet in your head section of your layout file:

<?php
$file=THEME . DS . Inflector::underscore($this->controller->name) . DS . 'css';
if (file_exists(CSS . $file . '.css'))
{
echo $html->css($file);
}

$file=THEME . DS . Inflector::underscore($this->controller->name) . DS . $this->controller->action;
if (file_exists(CSS . $file .'.css'))
{
echo $html->css($file);
}

$file=THEME . DS . Inflector::underscore($this->controller->name) . DS . 'ie';
if (file_exists(CSS . $file . '.css'))
{
echo '<!--[if lt IE 7]>';
echo $html->css($file);
echo '<![endif]-->';
}

$file=THEME . DS . Inflector::underscore($this->controller->name) . DS . $this->controller->action . '_ie';
if (file_exists(CSS . $file .'.css'))
{
echo '<!--[if lt IE 7]>';
echo $html->css($file);
echo '<![endif]-->';
}

?>
Advertisements

Comments»

1. scotfl - February 11, 2006

Wouldn’t it be easier to just provide the specific elements with a unique class.

Or even just wrap them in a div with a unique class? That would allow you to style those specific elements without spreading your css fom one end the webroot to the other.

Not to mention that it would be a more semantic markup because it wouldn’t depend on a given css file being magically available or unavailable.

2. rossoft - February 11, 2006

No, because my actions are generic, they are something like scaffolding. I can’t touch the view, but I want to modify the style automatically without touching any code (for example size of one column of a listing)

3. scotfl - February 11, 2006

Ah, it was the “I dislike writing the CSS directly in the .thtml file so I have done a little snippet code for doing this” that threw me. I thought you were choosing to not alter the View rather than being constrained from altering the View.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: