View に変数を割り当てる[FuelPHP1.7]

メモ:  Category:php

ビュー( + Template )を使った hello, world![FuelPHP 1.7]」では、 Controller_Template を継承することで View を使用しました。ここでは View への値の渡し方をみてみます。

以下の例では、 Controller_Template は使用しないで View::forge を使用して View を生成しています。

View への値の渡し方

例えば、次のような View を作成します。 (例:app/views/website/index.php)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?php echo $title ?></title>
</head>
<body>
<?php echo $content ?>
</body>
</html>

この View へ値を渡すには、主に 3 つの方法があります。

方法 1

class Controller_Website extends Controller
{

    function action_index()
    {
        $data = array();

        $data['title']='Sample FuelPHP 1.7';
        $data['content']='hello, world!';

        return View::forge('website/index',$data);
    }
}

方法 2

class Controller_Website extends Controller
{

    function action_index()
    {
        $view = View::forge('website/index');

        view->title = 'Sample FuelPHP 1.7';
        view->content = 'hello, world!';

        return $view;
    }
}

方法 3

class Controller_Website extends Controller
{

    function action_index()
    {
        $view = View::forge('website/index');

        view->set('tile','Sample FuelPHP 1.7');
        view->set('content','hello, world!');

        return $view;
    }
}

上記以外の方法に「 bind 」を使う方法がありますが、ドキュメントには次のような注意書きがあります。

※これらは出力のエンコーディングでクリーニングされないので、安全ではないと見なすべきです。

bluenote by BBB