Table of Contents
Smarty は色々な種類の変数を持っています。変数の種類は接頭辞の記号によって決まります (記号によって囲まれる場合もあります)。
Smarty 変数は、その値を直接表示したり 関数 の引数や 属性、 修飾子、 そして条件式の内部などで使用されたりします。 変数の値を表示するには、それを単純に デリミタ で囲み、デリミタ内に変数のみが含まれるようにします。
Example 4.1. 変数の例
{$Name}
{$product.part_no} <b>{$product.description}</b>
{$Contacts[row].Phone}
<body bgcolor="{#bgcolor#}">
Smarty 変数の値を手っ取り早く調べるには、 デバッギングコンソール を使用するとよいでしょう。
代入された変数は、先頭にドル記号 ($) がつきます。
Example 4.2. 割り当てられた変数
PHP のコード
<?php
$smarty = new Smarty();
$smarty->assign('firstname', 'Doug');
$smarty->assign('lastname', 'Evans');
$smarty->assign('meetingPlace', 'New York');
$smarty->display('index.tpl');
?>
index.tpl のソース
Hello {$firstname} {$lastname}, glad to see you can make it.
<br />
{* これは動作しません。変数名は大文字小文字を区別するからです。 *}
This weeks meeting is in {$meetingplace}.
{* こちらは動作します *}
This weeks meeting is in {$meetingPlace}.
出力は次のようになります。
Hello Doug Evans, glad to see you can make it. <br /> This weeks meeting is in . This weeks meeting is in New York.
PHP から割り当てられた連想配列を参照することもできます。 その場合は、ドット "." の後にキーを指定します。
Example 4.3. 連想配列の値にアクセスする
<?php
$smarty->assign('Contacts',
array('fax' => '555-222-9876',
'email' => 'zaphod@slartibartfast.example.com',
'phone' => array('home' => '555-444-3333',
'cell' => '555-111-1234')
)
);
$smarty->display('index.tpl');
?>
index.tpl のソース
{$Contacts.fax}<br />
{$Contacts.email}<br />
{* you can print arrays of arrays as well *}
{$Contacts.phone.home}<br />
{$Contacts.phone.cell}<br />
出力は次のようになります。
555-222-9876<br /> zaphod@slartibartfast.example.com<br /> 555-444-3333<br /> 555-111-1234<br />
配列に対してインデックスでアクセスすることもできます。 これは PHP 本来の構文と同じです。
Example 4.4. インデックスによって配列にアクセスする
<?php
$smarty->assign('Contacts', array(
'555-222-9876',
'zaphod@slartibartfast.example.com',
array('555-444-3333',
'555-111-1234')
));
$smarty->display('index.tpl');
?>
index.tpl のソース
{$Contacts[0]}<br />
{$Contacts[1]}<br />
{* you can print arrays of arrays as well *}
{$Contacts[2][0]}<br />
{$Contacts[2][1]}<br />
出力は次のようになります。
555-222-9876<br /> zaphod@slartibartfast.example.com<br /> 555-444-3333<br /> 555-111-1234<br />
PHP から割り当てられた オブジェクト
のプロパティにアクセスするには、->
記号の後にプロパティ名を指定します。