CakePHP Element操作

エレメントとは

Viewの一部を切り出して部品化したファイル
ctpファイルで保存し、Viewに組み込む

通常

エレメント

※~/src/Template/Element/test.ctp
<div>
 <?= echo(‘xxx’); ?>
</div>

ビュー

aaa
<?= $this->element(‘test‘); ?>
bbb

結果

aaa
xxx
bbb

パンくずリストのエレメント化&テンプレート化

パンくずリストについては「CakePHP View操作 Htmlヘルパー/パンくずリスト生成」参照
テンプレートについては「CakePHP View操作/テンプレート」参照

エレメント

※~/src/Template/Element/breadcrumbs.ctp
<div>
 <?=
  パンくずリスト最初のページ
  $this->Html->getCrumbs(‘ > ‘, [
    ’text’ => ‘1ページ目’,
    ’url’ => ‘/’,
    ’escape’ => false,
   ]);
 ?>
</div>

コントローラ

$this->autoRender = true;
$this->viewBuilder()->layout(‘Tests’);
$this->viewBuilder()->autoLayout(true);

※~/src/Template/Layout/tests.ctp
<html>
<body>
 <?php echo $this->element(‘breadcrumbs‘); ?>
 <?= $this->fetch(‘content’) ?>
</body>
</html>

ビュー

<?php
 $this->Html->addCrumb(‘2ページ目’, [‘controller’ => ‘~’, ‘action’ => ‘~’]);
 $this->Html->addCrumb(‘3ページ目’, ”);
?>

結果

1ページ目 > 2ページ目 > 3ページ目