0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

cakephp3のビューブロックについて

Last updated at Posted at 2021-05-27

これの知らなかった超絶便利機能があったのでメモ
自分の言葉でまとめますが、語弊があるかもですので参照するなら自己責任でお願いします

ビューブロックとは

継承してるView同士で特定のパーツを呼び出せる仕組み

view1.ctp
$this->start('block');
echo "hoge";
$this->end();
view2.ctp
<?= $this->fetch('block') ?>
<!--これを入れた位置に「hoge」が出力される-->

とcookbookには書いてます。

誤解してた

てっきり

  • 継承元で定義したブロックを
  • 継承先で呼び出す

しかできないのかなと思ってましたがよーーーくcookbookを見たところ、逆もできるそうです。
実用的な感じで言えば、

  • layoutとかで呼び出してるブロックを
  • template/以下のview内で書き換えられる。

何が嬉しいのか

これはつまりアクションに応じてlayoutの記述を書き換えることができるということ。

例えば

  • アクションごとに違う処理をjsで実行したい
  • しかしその記述箇所は一律でheadの中

という場合は

layout.ctp
<head>
<?= $this->fetch('action_script') ?>
<head>
top.ctp
<?php $this->start('action_script'); ?>
<script>
//TOPで実行したい何かの処理
</script>
<?php $this->end(); ?>
article.ctp
<?php $this->start('action_script'); ?>
<script>
//記事ページで実行したい何かの処理
</script>
<?php $this->end(); ?>

という書き方ができる。

うまいこと使えばよくある「コンテンツの性質に応じてlayoutファイルを分ける」という必要もなくなるかもしれない。

デフォルトの記述の意味

cakephp3の場合、layout/default.ctpにデフォルトで下記の記述があります。(多分)

<head>
    <title>
        <?= $this->fetch('title') ?>
    </title>
    <?= $this->fetch('meta') ?>
    <?= $this->fetch('css') ?>
    <?= $this->fetch('script') ?>
</head>

一方でページタイトルを設定する場合、

$this->assign('title', 'TOPです');

という書き方をするといいよ!!というcookbookの記述があります。

これができるのも上記の理由から、ということ。
metaとかscriptも同様。
上記の例はあくまで説明のためのものなので、スクリプトを書くならもっといいやり方があるかもです。
$this->assign('script', xxx);とか)

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?