インデントの設定(indent)
「indent」は文字列にインデントを設定します。文字列が複数行の場合は各行に対して同じインデントが設定されます。書式は次の通りです。
{$変数名|indent}
デフォルトでは4文字の空白がインデントとして設定されます。
1番目のパラメータでインデントとして挿入される空白文字の個数を指定できます。
{$変数名|indent[:個数]}
また空白の代わりのインデントとして設定される文字を指定することも出来ます。2番目のパラメータで指定して下さい。
{$変数名|indent[:個数[:文字]]}
HTML文として記述する場合に空白文字を何文字続けても1の空白文字としてしか扱われません。その為、空白文字を使ってインデントを行う場合には文字に「 」を指定して下さい。
具体的には次のように記述します。
{$msg|indent}
{$msg|indent:2}
{$msg|indent:2:'>'}
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?php
require_once('Smarty.class.php');
$smarty = new Smarty();
$smarty->template_dir = 'd:/smartysample/modifier/templates/';
$smarty->compile_dir = 'd:/smartysample/modifier/templates_c/';
$smarty->config_dir = 'd:/smartysample/modifier/configs/';
$smarty->cache_dir = 'd:/smartysample/modifier/cache/';
$smarty->assign('title', '修飾子のテスト');
$msg=<<<EOT
こんにちは
明日も晴れるでしょうか
ではまた
EOT;
$smarty->assign('msg', $msg);
$smarty->display('sample9-1.tpl');
?>
上記を「sample9-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥modifier」に保存します。
{* Smarty modifier/sample9-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>{$title}</h1>
<p>{$msg|nl2br|indent}</p>
<p>{$msg|nl2br|indent:2:' '}</p>
</body>
</html>
上記を「sample9-1.tpl」の名前で「D:¥smartysample¥modifier¥templates」に保存します。
そしてブラウザから「http://localhost/smarty/modifier/sample9-1.php」へアクセスして下さい。
今回のサンプルでは改行されていないとわかりにくい為、まず「nl2br」修飾子を適用してから「indent」修飾子を適用しています。
表示されたHTMLページのソースを確認してみます。
( Written by Tatsuo Ikura )
PHPBook