Cakephp2.1 ViewBlock view-inheritance

Post on 31-May-2015

3.413 views 0 download

description

CakePHP勉強会 2012春

Transcript of Cakephp2.1 ViewBlock view-inheritance

@mon_sat

ViewBlock - Viewの継承 -CakePHP2.1

https://gist.github.com/1983724 資料内のコード

1

@mon_sat

CakePHP1.x/2.0のViewLayout / View / Elements

LayoutviewファイルElements

2

@mon_sat

CakePHP1.x/2.0のView

3

@mon_sat

CakePHP1.x/2.0のView

4

@mon_sat

ViewBlockの基本子のViewBlockで assign(append, start/end) したHTMLを親のViewBlockで fetch する

5

@mon_sat

ViewBlockとはHTMLの「一部」(もしくは全部)各ViewBlockは親ViewBlockを持つLayout(親)view.ctp(子)と同様 必要に応じて何回層も入れ子にできる最上位のViewBlockがLayoutファイル

6

@mon_sat

ViewBlockのイメージ

7

ViewBlockの使用例

8

@mon_sat

viewファイルとは別の場所でh1タグを使用 ������������������ �����������

9

@mon_sat

viewファイルとは別の場所でh1タグを使用

任意のキー 親のViewBlockに渡す「値」

������������������ �����������

9

$this->assign($name, $value);上位ViewBlockにHTML(の一部)を渡す‘content’は$nameとして使えない

$this->fetch($name);下位ViewBlockで設定されたHTMLを取り出す$nameが存在しなければ空文字列

10

@mon_sat

</body>直前にJavaScriptを記述したい ������������������ �����������

11

$this->append($name, $value = null);任意のViewBlockの末尾にHTML(の一部)を加える

HtmlHelperのblockオプションarray(‘block’ => ‘name’)で、戻り値をViewBlockに格納HtmlHelper::css()やmeta()でも使用可能

12

@mon_sat

Side Bar に書き出す������������������ ������������

13

@mon_sat

Side Bar に書き出す������������������ ������������

13

$this->append($name);$this->start($name);$this->end()まで、HTMLを任意のViewBlockの末尾に加える入れ子にして(同時に)使用可能

$this->end();直近のViewBlockを閉じる

14

ViewBlock継承の使用例

15

@mon_sat

viewファイルのテンプレートを作って使い回す(継承する)viewファイルのテンプレート化で、よりDRYにViewを作成可能例: Layout > (template) > viewファイル

クラスを継承するようにviewファイルを継承可能

16

@mon_sat

viewのtemplateを利用する������������������ �����������

17

$this->extend($name);継承するViewBlockを指定する包含する親ViewBlockができる$nameの指定方法viewファイル(View/Posts/index.ctpの場合)‘/temp’・・・app/View/temp.ctp‘temp’・・・app/View/Posts/temp.ctp

Layoutファイル‘temp’・・・app/View/Layouts/temp.ctp

Elementファイル‘temp’・・・app/View/Elements/temp.ctp

18

$this->extend() による継承は、必要なだけ何度でも入れ子にできる

つまり、、、

19

まとめViewBlockでViewもDRYに

20

$this->assign($name, $value); $this->append($name, $value = null);

$this->append($name);$this->start($name);$this->end();

$this->fetch($name);

$this->extend($name);22

@mon_sat

自己紹介@mon_sat (twitter)株式会社ダイレクトサーチジャパンCakePHPによる開発が大好きチーム・モンブランサックスhttp://tipshare.info/

23