CakePHPのコントローラーとビューを使ってページを表示してみます。
ページの表示
/test/indexにアクセスしたときに、ページが表示されるようにしてみます。
まずはコントローラーをsrc\Controller内に作成します。
src\Controller\TestController.php
1 2 3 4 5 6 7 8 9 | <?php namespace App\Controller; class TestController extends AppController { public function index() { } } |
今回は/test/indexにアクセスしたときに表示するので、TestControllerのindexメソッドを作成しています。
次にビューを作成します。
src\Template内にTestディレクトリを作成して、その中にindex.ctpを作成します。
src\Template\Test\index.ctp
1 | < h1 >Hello World!!</ h1 > |
http://localhost:8765/test/indexにアクセスして、以下のように表示が確認できました。
/indexの場合は省略して、http://localhost:8765/testでアクセスすることもできます。
レイアウトの変更
デフォルトではsrc\Template\Layout\default.ctpがレイアウトに使われているので、レイアウトを新しく作成してみます。
src\Template\Layout\test-layout.ctp
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html lang= "ja" > <head> <meta charset= "UTF-8" > <title>test</title> </head> <body> <?= $this ->fetch( 'content' ) ?> </body> </html> |
<?= $this->fetch(‘content’) ?>部分にビューが表示されます。
作成したレイアウトが適用されるようにコントローラーを修正します。
src\Controller\TestController.php
1 2 3 4 5 6 7 8 9 10 | <?php namespace App\Controller; class TestController extends AppController { public function index() { $this ->viewBuilder()->layout( 'test-layout' ); } } |
ブラウザで確認すると、レイアウトが変更されているのが確認できました。
変数の設定
コントローラーで設定した変数をビューやレイアウトで使用してみます。
src\Controller\TestController.php
1 2 3 4 5 6 7 8 9 10 11 | <?php namespace App\Controller; class TestController extends AppController { public function index() { $this ->set( 'text' , 'Hello!!' ); $this ->viewBuilder()->layout( 'test-layout' ); } } |
コントローラーで設定した変数をビューやレイアウトで表示できるように修正してみます。
src\Template\Test\index.ctp
1 | <h1><?= $text ?></h1> |
src\Template\Layout\test-layout.ctp
1 2 3 4 5 6 7 8 9 10 | <!DOCTYPE html> <html lang= "ja" > <head> <meta charset= "UTF-8" > <title><?= $text ?></title> </head> <body> <?= $this ->fetch( 'content' ) ?> </body> </html> |
ブラウザで確認すると、ビューとレイアウトで表示されているのが確認できました。
【参考サイト】
コメントが承認されるまで時間がかかります。