ysku's blog

ウェブ・無線通信・組み込みとか

CakePHP 【bootstrapの使用】

簡単に画面デザインをおしゃれにさせたかったので、bootstrapを試してみる事にしました。

今回は自分が試した方法を記載したいと思います。

大まかな流れ

まず、以下のURLからプラグインをダウンロードしてきます。
https://github.com/slywalker/TwitterBootstrap/archive/master.zip
名前をTwitterBootstrapに変更して、app/Pluginに移動させます。

app/Plugin/TwitterBootstrap/View/Layouts/default.ctpを
bootstrap.ctpに名前を変更してapp/View/Layoutsに配置します。

プラグインを有効にするためにapp/Config/bootstrap.phpに以下の記述を追加します。

CakePlugin::load(array(‘TwitterBootstrap'));


次に、

Bootstrap · The most popular HTML, CSS, and JS library in the world.
ここからbootstrap.zipをダウンロードし、展開すると
bootstrap
というフォルダが作成されます。

このフォルダ内のcss、js、imgの中身を丸ごとapp/webroot/css、js、imgにそれぞれコピーします。
フォルダの中身を丸ごと他のフォルダに入れるコマンドは以下の通りです。

# cp -Rpf dir1/. dir2

これで、dir1の中身が丸ごとdir2にコピーされます。


デザインを反映させたいページのコントローラーに以下の記述を追加する事でレイアウトを変更する事が出来ます。

$this->layout = ‘レイアウト名’; 
実際に試してみる

以下のURLのデザインを使用して試してみます。
Bootswatch: Free themes for Bootstrap

Themesで好きな画面を選択してDownloadでcssファイルを取得します。
今回はcosmoを選択して、cosmo.bootstrap.cssと設定しました。

これをapp/webroot/cssに移動させます。


次に、デザインを反映させたい画面のコントローラーに以下を記載します。

public function beforeFilter() {
        parent::beforeFilter();
        $this->layout = 'bootstrap';
}


最後に、ビューの例は以下の様になります。

<div class="row">
<div class="col-lg-6">
<div class="well bs-component">
<div class="form-group">
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User', array(
	'action' => 'login',
	'class' => 'form-horizontal'
	)); 
?>
<fieldset>
<legend>
<?php echo __('ユーザ名とパスワードを入力してください'); ?>
</legend>
<div class="form-group">
<div class="col-lg-10">	
<?php
	echo $this->Form->input('username', array(
		'class' => 'form-control'
	));
?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<?php
	echo $this->Form->input('password', array(
		'class' => 'form-control'
	));
?>
</div>
</div>
</fieldset>
<?php 
	$options = array(
		'label' => 'Login',
		'class' => 'btn btn-primary'
	);
	echo $this->Form->end($options); 
?>
</div>
</div>
</div>
</div>


結果的に以下の様な画面が作成出来ると思います。
f:id:yusuke1581:20140916040557p:plain

簡単ですが、以上が、bootstrapの使い方になります。