Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are URLs handled inside the CSS file in CakePHP so they reference the correct location?

I am designing a website using CSS Files a lot, but I have several occurrences of background images, images for bullets in lists and I will probably find another need for the css url() function.

But, in cake, all URL should be handled by the Route::url() function, in several ways, being most common the $html->url()

But my problem is that CSS Files are not interpreted by PHP. How I can create a CSS File containing something like:

div.coolbg {
  background-image: url('<?= $html->url("/img/coolbg.jpg") ?>');
}

See, my last option is to import the css file inline on the layout so it can be interpreted. But I highly prefer to use a more "Cake" approach.

Thanks!

like image 955
Fernando Barrocal Avatar asked Feb 04 '09 18:02

Fernando Barrocal


3 Answers

You don't need to use $html->url() in your css file, consequently you don't need to parse the CSS files through PHP or create a CssController.

If your cake app is installed in your virtual hosts DocumentRoot, just make all the paths to images absolute from the webroot. e.g.

div.coolbg {
  background-image: url(/img/coolbg.jpg);
}

This will apply the image at app/webroot/img/coolbg.jpg to your

If your cake app is not installed in the virtual hosts DocumentRoot, i.e. you access your cake app via a URL like http://www.domain.com/myapp/, then you make the path to the image relative to the css file. Check out the style rules in app/webroot/css/cake.generic.css e.g.

#header h1 {
background:#003D4C url(../img/cake.icon.gif) no-repeat scroll left center;
color:#FFFFFF;
padding:0 30px;
}

This works because style sheets live in the app/webroot/css/ directory, and image live in the app/webroot/img/ directory, so the path "../img/cake.icon.gif" comes up out of the css directory, then back down into the img directory.

like image 126
neilcrookes Avatar answered Oct 23 '22 20:10

neilcrookes


I would definately go for the solution suggested by zam3858. And if you don't like to have your images in two distinct locations, create a symbolic link in the css directory that points to the images. Like this:

$ cd app/webroot/css 
$ ln -s ../img .

Now, the image paths will be resolved correctly for both the html helper and style sheets:

// css:
url(img/image.png);

// view.ctp
echo $html->image('image.png');

It may not be the cakiest solution, but it doesn't look like cakephp provides one.

like image 42
Bram Avatar answered Oct 23 '22 21:10

Bram


Change the line with background to

background:url(../img/menu_027_l.jpg) no-repeat left;
like image 30
Anders Avatar answered Oct 23 '22 20:10

Anders