Mach3.laBlog

CodeIgniterの出力にMustacheを使ってみる

この記事は賞味期限切れです。(更新から1年が経過しています)

シンプルで軽量なPHPフレームワーク、CodeIgniterのビューで
これまた軽量なMustacheを使用してみるメモ。

CodeIgniter + Mustache

CodeIgniterのビューファイルではプレーンなPHPを書きますが、
Mustacheを読み込んで使用する事で、
より簡単な、見通しの良いビューファイルが出来上がるのでは! と思いやってみました。

普通にライブラリとして読み込む

配置する

執筆時からMustacheのバージョンが変わり、単ファイルではなくなっているため、手順が大きく変わる可能性があります。 (2012/10/25)

まずはPHP版のMustacheをダウンロードしてきます。

» bobthecow/mustache.php · GitHub

ダウンロードしてきたMustache.phpを、
system/application/libraries/ にコピーします。
ここは、CIのユーザーライブラリを格納しておくお決まりの場所です。
cf) ライブラリの作成 : CodeIgniter ユーザガイド 日本語版

簡単な例

$this->load->library( "mustache" );

echo $this->mustache->render(
    // 第一引数はテンプレート(文字列)
    "Hello, I am {{name}}",
    // 第二引数はテンプレートに渡す連想配列
    array( "name" => "HogeFuga" )
);
// Hello, I am Hogefuga

文字列をテンプレートとして出力してみた例。

ビューファイルを読み込んで出力する

/* コントローラ内 */
$this->load->library( "mustache" );
$this->mustache->render(
    $this->load->view( "example.php", null, true ),
    array(
        "members" => array(
            array( "name" => "太郎" ),
            array( "name" => "花子" ),
            array( "name" => "ジョンソン" )
        )
    )
);

CIおなじみの$this->load->view()の第三引数にtrueを渡すと
結果を文字列で受け取れるのでそれを使います。

<!--ビューファイル(example.php)-->
<ul>
    {{#members}}
    <li>わたしが{{name}}です!</li>
    {{/members}}
</ul>

出力結果

<!--出力結果-->
<ul>
    <li>わたしが太郎です!</li>
    <li>わたしが花子です!</li>
    <li>わたしがジョンソンです!</li>
</ul>

Controllerを拡張してみる

毎度$this->mustache->render()と、$this->load->view()を
両方呼ぶのが面倒だと感じたなら、
コアクラスのControllerを拡張してしまう手もあります。

/*
 * 2.0でおき場所がかわったので注意
 * 1.7.x → system/application/libraries/MY_Controller.php
 * 2.0 → system/application/core/MY_Controller.php
 */
class MY_Controller extends Controller {

    public function __construct(){
        parent::__construct();
        $this->load->library("mustache");
    }

    public function _render( $name, $data = null, $return = false ){
        $res = $this->mustache->render(
            $this->load->view( $name, null, true ),
            $data
        );
        if( $return ) return $res;
        echo $res;
    }
}

上の例では、$this->_render()を使う事で、
$this->load->view()と同じ要領でビューファイルを
Mustacheを通して出力する事が出来ます。

$this->_render(
    "example.php",
    array( "name" => "foobar" )
);

まとめ

単純な出力しか出来ないので場合によっては不向きですが、
他言語とテンプレートの共有が出来るなんていう利点もあったり。
なかなか悪くない組み合わせな気がします。

コメント

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

*