Smarty - データバインディング

Advertisement

バインディング

テンプレート変数({$xxx})に対して値を設定することを、バインディングという。バインディングの用途により、テンプレート変数の記述方法が異なる。

テンプレート変数記述方法一覧
{$sample}シンプルな書き方
{$sample[1]}配列にインデックスでアクセス
{$sample.name}配列にkey値でアクセス
{$sample.$name}配列にkey値でアクセス(keyが変数)
{$sample->name}オブジェクトのプロパティにアクセス
{$sample->age()}オブジェクトのメソッドにアクセス

テンプレート変数{$sample}に値を設定する場合、プログラムでassign("sample","値")とする。また、{$sample[1]}の場合は、assign("sample",配列)のように、配列を設定する。

サンプル

テンプレートファイル(templates/templatevariable.tpl)
<html>
<head>
<title>sample</title>
</head>
<body>
<ul>
<li>{$name}</li>
<li>{$age[2]}</li>
<li>{$emp.id}</li>
<li>{$dept->name}</li>
<li>{$dept->type()}</li>
</ul>
</body>
</html>

プログラム(templatevariable.php)
<?php
require_once('Smarty/Smarty.class.php');

$smarty = new Smarty;
$smarty->assign("name", "ore");
$smarty->assign("age", array(1,2,3,4,5));
$smarty->assign("emp", array(id=>"0001", name=>"john"));

class Dept{
    var $name = "tinyboy";
    function type(){
        return "manager";
    }
}

$smarty->assign("dept", new Dept());
$smarty->display('templatevariable.tpl');
?>

結果
・ore
・3
・0001
・tinyboy
・manager

Advertisement

ショートカット

634トップページ
このカテゴリのトップページに戻る
634ラボ

サイト検索

Google

Web サイト内

Y!ログール