Smartyの使い方2

概要

せっかくなのでもう少しSmartyのお勉強。

目次

テンプレートファイルのコメント

テンプレートファイル内のコメントタグは {* *} で囲んで記述します。

{* これはコメントです *}
{* 
これもコメントです
さらにコメントです
*}

テンプレートファイルにPHP変数を読み込む。

テンプレートファイル内にPHPで設定した変数を読み込む基本的な構文

{$foo}         <-- 変数 $foo を表示する
{$foo|escape}  <-- 変数 $foo に含まれる & " ' < > といった特殊文字についてエスケープ処理をして表示する
{$foo[0]}      <-- 配列 $foo の0番目の要素を表示する
{$foo.bar}     <-- 配列 $foo の"bar"というキーに対応する値を表示する  $foo['bar']
{$foo.$bar}    <-- 配列 $foo の変数のキーに対応する値を表示する  $foo[$bar]
{$foo->bar}    <-- オブジェクト $foo のプロパティ"bar"を表示する
{$foo->bar()}  <-- オブジェクト $foo のメソッド"bar"の戻り値を表示する
{#foo#}        <-- configファイル変数"foo"を表示する
{$smarty.config.foo} <-- configファイル変数"foo"を表示する  {#foo#}と同じ

テンプレートファイルに別のテンプレートファイルを読み込む

テンプレートファイル内に別のテンプレートファイルを読み込むには、テンプレートファイルをincludeします。

 {* var/www/private/smarty_sample_tpl/templates/index.tpl *}

{include file='header.tpl'} ←header.tpl の読み込み

こんにちは、{$name|escape}さん。ようこそ Smarty の世界へ!

{include file='footer.tpl'} ←footer.tpl の読み込み
 {* var/www/private/smarty_sample_tpl/templates/header.tpl *}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja" lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=Shift_JIS" />
<title>Smartyのサンプルプログラム</title>
</head>
<body>
 {* var/www/private/smarty_sample_tpl/templates/footer.tpl *}
</body>
</html>

投稿日:

ページのトップへ戻る