CakePHPでBootstrapを使う
CakePHP3のCSSフレームワークは標準では「Foundation for Sites」(ファンデーション)ですが、日本で特に使用されている「Bootstrap」(ブートストラップ)を使用することも可能です。
1. 使い方
今回紹介するコードは一部抜粋です。完全なコードはオープンソースの掲示板システム(Bootstrapデザイン)をご覧ください。 ※デモはこちら
1-1. Bootstrapの配置
webroot/cssに配置します。
1-2. src/View/AppView.php
AppView.phpでCakePHPのテンプレートを変更する。
<?php namespace App\View; use Cake\View\View; class AppView extends View { public function initialize() { // ---------------- // Bootstrap仕様 // ---------------- // "Form"のerrorClass、templatesなどのデフォルト設定は // vendor\cakephp\cakephp\src\View\Helper\FormHelper.phpの$_defaultConfigを参照 // エラー時のinputのclass設定 $this->loadHelper('Form', [ 'errorClass' => 'is-invalid', ]); // templatesの内容を変更する if ($this->request->getParam('action') == "index"){ // Questions(検索用) if ($this->request->getParam('controller') == "Questions"){ $this->Form->setTemplates([ 'inputContainer' =>'<div class="form-group row">{{content}}</div>', 'input' => '<div class="col-sm-10"><input type="{{type}}" name="{{name}}"{{attrs}}/></div>', ]); // LangTypes(検索用) }else{ $this->Form->setTemplates([ 'inputContainer' =>'{{content}}', ]); } }else{ // 登録/更新 $this->Form->setTemplates([ 'inputContainer' =>'<div class="form-group">{{content}}</div>', 'inputContainerError' =>'<div class="form-group">{{content}}{{error}}</div>', 'error' => '<div class="text-danger" style="font-size:90%">{{content}}</div><p></p>' ]); } // "Paginator"のtemplatesなどのデフォルト設定は // vendor\cakephp\cakephp\src\View\Helper\PaginatorHelper.phpの$_defaultConfigを参照 // templatesの内容を変更する $this->Paginator->setTemplates([ 'prevActive' => '<li class="page-item"><a class="page-link" href="{{url}}" rel="prev">{{text}}</a></li>', 'prevDisabled' => '<li class="page-item disabled"><span class="page-link">{{text}}</span></li>', 'number' => '<li class="page-item"><a class="page-link" href="{{url}}">{{text}}</a></li>', 'current' => '<li class="page-item active"><span class="page-link" >{{text}}</span></li>', 'nextActive' => '<li class="page-item"><a rel="next" class="page-link" href="{{url}}">{{text}}</a></li>', 'nextDisabled' => '<li class="page-item disabled"><span class="page-link">{{text}}</span></li>', ]); } }
1-3. src/Template (ビューテンプレート側)
echo $this->Form->control('name', ['label' => ['text' => '名前'], 'class' => 'form-control']); echo $this->Form->control('keywords', ['label' => ['text' => 'キーワード'], 'class' => 'form-control']);
1-4. src/Template/Element/Flash (フラッシュ)
// error.ctp <?php if (!isset($params['escape']) || $params['escape'] !== false) { $message = h($message); } ?> <div class="alert alert-danger" onclick="this.classList.add('d-none');" id="msg_alert"><?= $message ?></div> // success.ctp <?php if (!isset($params['escape']) || $params['escape'] !== false) { $message = h($message); } ?> <div class="alert alert-success" onclick="this.classList.add('d-none')" id="msg_notice"><?= $message ?></div>
スポンサーリンク
関連記事
公開日:2021年02月11日
記事NO:02883