Smarty – ループ内でbreak, continueを利用する

8月 27, 2010 · Posted in PHP, Smarty · Comment 

タグ{php}と、phpコードのbreak(continue)を組み合わせることで、テンプレート内ループでもbreak,continueの処理が可能となります。

書き方

{php}break;{/php}

{foreach from=$dataList key="key" item="data" name="list"}
    {if $data->name eq null}
        {php}continue;{/php}
    {/if}

   名前:{$data->name}<br>
{/foreach}

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

1月 1, 2003 · Posted in Smarty · Comment 

バインディング

テンプレート変数({$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

Smarty – コメント

1月 1, 2003 · Posted in Smarty · Comment 

テンプレート内にコメントを記述する

テンプレート内にSmaryのコメントを記述することができる。
このコメントは、エンジンの解析結果には出力されない。

書式

{* コメント *}

{* コメント *}

{*
複数行の
コ
メ
ン
ト
*}

次ページへ »