CakePHP

Smartyテンプレート内でrequestActionを使う方法

CakePHPのマニュアルに載っているrequestAcrtionをViewテンプレート内で使う方法ですが、SmartyViewを使うとそっくり同じにはできません。ちょっと試して代替方法で出来たのでメモ。
CakePHP 1.2.3.8166 + SmartyView 1.2.1で確認。

CakePHPマニュアルの例を取ってみます。

requestAction :: その他の便利なメソッド :: コントローラのメソッド :: コントローラ :: CakePHPによる開発 :: マニュアル :: 1.2 Collection :: The Cookbook

まずはエレメントのテンプレートファイル。

views/elements/latest_comments.ctp

$comments = $this->requestAction('/comments/latest');
foreach($comments as $comment) {
    echo $comment['Comment']['title'];
}

これを.tplの拡張子に改名して下記のように書き換えます。

views/elements/latest_comments.tpl

{php}$this->assign('comments', View::requestAction('/comments/lastest');{/php}
{foreach from=$comments item=comment}
    {$comment.Comment.title}
{/foreach}

$thissmartyのメソッドが使えます。$this->requestAction()を使う代わりにView::requestAction()を呼んでいるのがミソです。
次にエレメントの呼び出し元を書き換えます。もともとは

echo $this->element('latest_comments');

となっているのをSmarty書式に

{$view->element('latest_comments')}

と書き換えます。ほぼ一緒。

コントローラはそのままでOKです。
たまたま出来たんで完全に大丈夫かは保障できませんが一応問題なく動いてます。
以上。

スポンサーリンク
管理人

システムえんじにゃー🐈
趣味はエレキギターなど。作曲したい。
WoWs/プリコネ
記事に関する質問はお気軽にどうぞ。

surface0 (さーふぇす)をフォローする
surface0 (さーふぇす)をフォローする

コメント

タイトルとURLをコピーしました