第8回では、
- レイアウトの作成
- ページタイトルの設定
- アクセスしやすいURLの設定
(Routes)
レイアウトの作成
「レイアウト」
レイアウトとビューの関係は以下のイメージです。

レイアウトファイルは、
CakePHPは、
cakeディレクトリ以下のファイルとを書き換えてしまうと、
なお、
では、
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title><?php echo h($title_for_layout); ?></title>
<?php echo $html->css('cake.generic');?>
</head>
<body>
<div id="container">
<div id="header">
<h1>ToDo App</h1>
</div>
<div id="content">
<?php echo $content_for_layout; ?>
</div>
</div>
</body>
</html>
このレイアウトファイルでページを開くと以下のように表示されます。

変化は少ないですが、
では、
<title><?php echo h($title_for_layout); ?></title>
ここではページタイトルを定義しています。h関数はCakePHPが定義したhtmlspecialchars関数へのエイリアスです
<?php echo $html->css('cake.generic');?>
こちらはcssファイルを読み込むlink要素を出力しています。今回のコードでは、
<link rel="stylesheet" type="text/css" href="/~gihyo/todo/css/cake.generic.css" />
cake.
<?php echo $content_for_layout; ?>
$content_
レイアウトのPHPコードは以上です。
レイアウトと表示出力のコントロール
デフォルト以外のレイアウトファイルは、
$this->layout = 'example';
また、
$this->render('ビュー名', 'レイアウト名');
たとえば、
$this->render('index2', 'example');
ビューだけを変更したいときは以下のように記述します。
$this->render('index2');
なお、
$this->autoRender = false;
このあとにrenderメソッドを実行しなければ、
ページタイトルの設定
ページタイトルはコントローラの$pageTitleプロパティに設定します。たとえば、
$this->pageTitle = 'タスク一覧';
今回のアプリではTasksコントローラのindexアクション
<?php
class TasksController extends AppController {
var $name = 'Tasks';
var $uses = array('Task');
var $helpers = array(
'Javascript',
'Ajax',
);
function index() {
$this->set('yet_tasks', $this->Task->findAllByStatus('yet', null,'Task.created ASC'));
$this->set('done_tasks', $this->Task->findAllByStatus('done',null, 'Task.modified DESC'));
$this->pageTitle = 'タスク一覧';
}
function add() {
if (empty($this->data)) return;
$this->Task->save($this->data, true, array('content', 'created','modified'));
$this->set('yet_tasks', $this->Task->findAllByStatus('yet', null,'Task.created ASC'));
$this->layout = 'ajax';
}
function done($id) {
if ($this->Task->findById($id)) {
$this->Task->id = $id;
$this->Task->save(array('status' => 'done'));
}
$this->redirect('/tasks');
}
function edit($id) {
$task = $this->Task->findById($id);
if (!$task) {
$this->redirect('/tasks');
return;
}
if (!empty($this->data)) {
$task['Task']['content'] = $this->data['Task']['content'];
$this->Task->save($task);
}
$this->set('task', $task);
$this->pageTitle = 'タスクの編集 Id:' . $id;
}
function del($id) {
$this->Task->del($id);
$this->redirect('/tasks');
}
}
コードを追加したらブラウザのタイトル表示部分を確認してみてください。
アクセスしやすいURLの設定(Routes)
これまで、
URLの設定はmod_
app/
…
$Route->connect('/', array('controller' => 'pages', 'action' => 'display', 'home'));
…
以下に変更します。
…
$Route->connect('/', array('controller' => 'tasks', 'action' => 'index'));
…
これで
今回設定したRoutesは単純なものですが、
ToDoアプリの開発は以上です
今回の内容で、
次回以降は、