PHPTALのカスタムモディファイア if, eq を作ってみた
PHPTALと格闘すること数日。PHPTALにはif文っぽい表現をするにはPHPモディファイアを使わざるをえないことに悩みました。
condとeqがあればいいのに。なぜだろう。これが TAL-way なのか。でも欲しい。PHPモディファイアは使いたくない。でも。でも。。。
んが作った。
if, eq モディファイア
function phptal_tales_if( $src, $nothrow ) { list($if_part, $right) = explode('?', $src, 3); if (strpos($right,'|')) { list($then_part, $else_part) = explode('|', $right, 2); } else { $then_part = $right; $else_part = 'null'; } return '('.phptal_tales($if_part, $nothrow).') ? '.phptal_tales($then_part, $nothrow).' : '.phptal_tales($else_part, $nothrow).''; } function phptal_tales_eq( $src, $nothrow ) { list($left, $right) = explode(' ', $src, 2); return '('.phptal_tales($left, $nothrow).' == '.phptal_tales($right, $nothrow).' )'; }
condでなくifにした。
使い方
コントローラー
$people = array(); $people[] = (object)array("name"=>"foo", "phone"=>"01-344-121-021"); $people[] = (object)array("name"=>"bar", "phone"=>"05-999-165-541"); $people[] = (object)array("name"=>"baz", "phone"=>"01-389-321-024"); $people[] = (object)array("name"=>"quz", "phone"=>"05-321-378-654"); $template->people = $people; echo $template->execute();
テンプレート
<span tal:replace="if: eq:people/0/name people/0/name ? string:then " >default</span> :then <br/> <span tal:replace="if: eq:people/0/name people/1/name ? string:then " >default</span> :null <br/> <span tal:replace="if: eq:people/0/name people/0/name ? string:then | string:else" /> :then <br/> <span tal:replace="if: eq:people/0/name people/1/name ? string:then | string:else"/> :else <br/> <span tal:replace="if: exists:people/1 ? string: people/1 exists | string: people/1 not exists " >default</span> :people/1 exists <br/> <span tal:replace="if: exists:people/100 ? string: people/100 exists | string: people/100 not exists " >default</span> :people/100 not exists <br/>
というわけで
PHPTALの道から外れるかもしれないが作ってすっきりした。これならいろいろ表現できそう。もとからあるexistsも活かせるし、neもすぐ作れるね。