LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【CakePHP3】テンプレートで画面表示

Posted at

今回はcssやjsを読み込んでビュー表示させます。

ビュー描画時に利用されるファイル(css/js/img)は、webroot配下に格納。

ビューファイル内で各種ファイル読み込み時は、HtmlHelperを利用。

//css
<?= $this->Html->css('bootstrap.css') ?>

//js
<?= $this->Html->script('bootstrap.js') ?>

//img
<?= $this->Html->image('carrer/cakephp3.jpg') ?>

他にもmeta属性やリンク(aタブ)も記述することが出来ます。

ビューの継承

jsやcss読み込みなど、共通ロジックは基底ビューに定義するのが好ましい。

基底ビューはTemplate配下に格納します。

//src/Template/Layout/layout.ctp

<!DOCTYPE html>
<html>
    <head>
        <?= $this->Html->charset() ?>
        <?= $this->Html->meta('icon') ?>        
        <?= $this->Html->css('bootstrap.css') ?>
        <?= $this->Html->script('jquery-3.1.1.min.js') ?>
        <?= $this->Html->script('bootstrap.js') ?>
    </head>
    <body>
        <?= $this->fetch('content') ?>
    </body>
</html>

Controllerから呼び出されるビューは、$this->fetch(‘content’) で読み込む。

継承元のテンプレートビュー呼び出し

Controller内で以下のように呼び出すことが出来ます。

class TestController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->viewBuilder()->layout('layout');
    }

    public function index()
    {
        // 処理
    }

initializeでlayoutが呼び出し後、各アクションのテンプレートが呼び出されます。

Controller内で別ビューを表示

render()メソッドの第一引数にビュー名を指定、別のビューを呼び出せます。

namespace App\Controller;

use App\Controller\AppController;

class TestController extends AppController
{
    public function initialize()
    {
        parent::initialize();
        $this->viewBuilder()->layout('layout');
    }

    public function index()
    {
        $this->set('var', "test");        
        $this->render('/Test/index2');
    }
}

index()を呼び出すと通常であればindex.ctpが呼び出されます。

上記の場合、第一引数にビュー名を指定したので、index2.ctpが呼び出されます。

0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up