文字列を指定の形式にフォーマット(string_format)
広告
「string_format」は文字列を指定の形式にフォーマットします。主に数値が含まれる文字列が対象となります。書式は次の通りです。
{$変数名|string_format:フォーマット文字列}
1番目のパラメータでフォーマット形式を表すフォーマット文字列を指定します。フォーマット文字列はPHPの「sprintf」関数で使用するものと同じです。詳しくは「指定の形式にフォーマット(sprintf)」を参照して下さい。
具体的には次のように記述します。
{$num|string_format:"%05d"}
{$num|string_format:"%.3f"}
サンプルプログラム
では簡単なサンプルプログラムを作成して試してみます。
<?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', '修飾子のテスト');
$smarty->assign('num', "137");
$smarty->assign('fnum', "45.265");
$smarty->display('sample12-1.tpl');
?>
上記を「sample12-1.php」の名前で「(Apacheドキュメントルート)¥smarty¥modifier」に保存します。
{* Smarty modifier/sample12-1.tpl *}
<html>
<head>
<title>Smarty Test</title>
</head>
<body>
<h1>{$title}</h1>
<p>{$num|string_format:"%05d"}</p>
<p>{$fnum|string_format:"%.2f"}</p>
</body>
</html>
上記を「sample12-1.tpl」の名前で「D:¥smartysample¥modifier¥templates」に保存します。
そしてブラウザから「http://localhost/smarty/modifier/sample12-1.php」へアクセスして下さい。
( Written by Tatsuo Ikura )
PHPBook