2017年6月22日木曜日

[cakephp 2.x]スタイルシートをViewに置く方法

Config/routers.phpに次の1行を加える
1
Router::connect("/css/*", array( "controller" => "css", "action" => "index" ));
コントローラーを追加する Controller/CssController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
App::uses('AppController', 'Controller');
class CssController extends AppController{
 public function index(){
 
  $this->layout = false;
  $this->response->type( "text/css" );
  // ビューファイルから@charsetを省略する場合
  // echo "@charset \"UTF-8\"; " . PHP_EOL;
 
  $path = func_get_args();
  $fileName = implode('/', $path);
 
  $this->render( $fileName );
 }
}
ビューファイルはView/Css/css以下に置く View/Css/css/svg/background.ctp
1
2
3
4
5
6
7
8
9
@charset "UTF-8";
/* =====================================
  SVG背景画像
===================================== */
/*  ボタン
================================ */
.btn--search:before {
  background-image: url("<?php echo $this->Html->url('/img/icn-search.svg'); ?>");
}
cakephpをサブディレクトリcakephpにインストールした場合以下のようにみえる。 //example.com/cakephp/css/svg/background.css
1
2
3
4
5
6
7
8
9
@charset "UTF-8";
/* =====================================
  SVG背景画像
===================================== */
/*  ボタン
================================ */
.btn--search:before {
  background-image: url("/cakephp/img/icn-search.svg");
}