NO プログラム NO LIFE

ayanamiの備忘録

[PHP]Yii + Ajaxで部分テンプレートを表示する

Yiiフレームワークを利用して、部分テンプレートを実装する方法。foobarに書き換えてみる。

まずはベースとなるbase.tpl

1
2
3
<script type="text/javascript" src="{Yii::app()->request->baseUrl}/js/ajax.js"></script>
<div id="button">fooをbarに書き換える</div>
<div id="replace-area">foo</div>

続いて、テンプレートとなるpart.tpl

1
2
<input id="base-url" type="hidden" value={$baseUrl}>
bar

テンプレートをレンダリングするajax_content.php

1
<?php echo $data; ?>

base.tplで読み込んでいるajax.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
$(document).ready(function() {'use strict';

    $(document).on('click', '#button', function() {
        toBar();
    });

    function toBar() {
        return $.ajax({
            type: "GET",
            url: $("#base-url").val(),
            data: {
                ajaxRequest: "ajaxRequest"
            },
            complete: function(response) {
                var json = $.parseJSON(response.responseText);
                $("#replace-area").empty();
                if (json.data.content.length > 0) {
                    $("#replace-area").append(json.data.content);
                };
            }
        });
    };
});

最後にAjaxController.phpCController#renderPartial()を利用する。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public function actionIndex()
{
    // Ajaxのリクエストを判定。
    if (isset($_GET['ajaxRequest']))
    {
        // 部分テンプレートを文字列として取得。
        // 第3引数をtrueにすることで、文字列として取得できる。
        $content = $this->renderPartial('part', array(
                'baseUrl' => Yii::app()->createUrl('base'),
            ), true);

        $data = array(
                'content' => $content,
            );

        // アウトプットを文字列としてレンダリング。
        // 第4引数をtrueにすることで、文字列としてレンダリングできる。
        $this->renderPartial('ajax_content',
              CJSON::encode(array('data'=>$data)), false, true);
    }
}