Adding image to css background in Cakephp2

Somewhat, as I arrived in various programming languages, I remember checking and learning a lot while using that language, but as time goes by I forget it.

I sometimes leave notes on what I checked about cakephp2 at work, but I do not remember where I left the memo so I can not even remember.

So I thought about trying to keep it on my blog this time.
…… Oh, and I’d like to write down my daily routine and miscellaneous things.

Well good. Essence.


Handling images in cakephp2

Even if you move the location of the image, you can easily access it by rewriting the path of “App.imageBaseUrl”.

However, if you are browsing an image from a CSS file in webroot / css / with background-image etc, it will be tough if the location of the image moves.
It is necessary to rewrite image paths in all CSS.
(This is because the parameter “App.imageBaseUrlcannotot be used in css file.)

Of course, we can not deal with the case of separating image servers in the local environment and the production environment for the purpose of load balancing of the Web server.

Therefore, there is a method to dynamically generate CSS.
This can be done easily using the View mechanism.

First, add the following description per core.php so that the view cache is valid.
If there is a description like (Configure :: write (‘debug’, 2);, please describe it below it.)

if(Configure::read('debug') > 0){  
	Configure::write('Cache.check', false);  
} else {  
	Configure::write('Cache.check', true);  
}

 

<?php

App::uses('AppController', 'Controller');

class CssController extends AppController
{
	var $cacheAction = array(
		'index' => 86400,	
	);

	public function index()
	{
		$this->response->type('css');
		$this->layout = 'css';
		$this->render($this->request->query['css']);
	}
}

As long as the content of css changes every time you refresh the display, caching the View is safe in terms of performance. We also prepare a layout corresponding to the above in View / Layouts /.

<?php
/**
 * css.ctp
 */
	echo $this->fetch('content');
?>

Next is View. Prepare for View / Css /.

body {
	background-image: url("<?php echo $this->Html->assetUrl('vegi.jpg', array('pathPrefix' => Configure::read('App.imageBaseUrl'))); ?>");
}

Using Helper :: assetUrl, we use App.imageBaseUrl to generate the appropriate URL here. So by accessing http: // vegi.com / Css /? Css = sample you can get css with the App.imageBaseUrl setting applied to the background-image like below.

body {
	background-image: url("/img/vegi.jpg");
}