備忘録

webの備忘録のために

CakePHP3 エレメント

前回レイアウトを作成したが、今回はそのレイアウトを作成する際に便利な機能 エレメントについて。

エレメントは端的に言うと、レイアウトの内部にはめ込んで利用するもの。 これはTemplateフォルダにあるElementというフォルダの中に用意されている。

-サンプルソースコード

レイアウトテンプレート(Template/Layout/hello.ctp)

<body>
<div id="container">
    <div id="header">
        <?=$this->element("header") ?>
    </div>
    <div id="content">
        <?=$this->fetch('content') ?>
    </div>
    <div id="footer">
        <?=$this->element("footer1") ?>
    </div>
</div>
</body>

こちらの記述でそれぞれのTemplate/Element/Hello/の中に格納されているファイルを読み込む。

<?=$this->element("header") ?>

→ Template/Element/Hello/header.ctp 読み込む

さらにエレメントの中身で Template/Element/Hello/header.ctp

→ <?=$msg ?>

このような形で変数を持たせておいて、コントローラのほうで変数に値をset関数で変数を準備し、読み込ませることも可能。

-サンプルソースコード

<?php
namespace App\Controller;

class HelloController extends AppController {

    public function initialize(){
        $this->name = 'Hello';
        $this->viewBuilder()->autoLayout(true);
        $this->viewBuilder()->layout('Hello');
    }

    public function index(){
        $this->set('msg','ヘッダーエレメント!!');
    }

}