ラベル Smarty の投稿を表示しています。 すべての投稿を表示
ラベル Smarty の投稿を表示しています。 すべての投稿を表示

2010年12月1日水曜日

php,smarty,mysql,javascriptでゼロ埋め

※javascriptも追加しました。

ゼロ埋めとかゼロパディングと言われるものです。
よく忘れてしまうのでまとめておきます。

■php
echo sprintf("%05d", $number);

echo str_pad($number, 5, "0", STR_PAD_LEFT);

引数をひとつ以上渡すことも可能。
echo sprintf("%04d-%02d-%02d", $year, $month, $day);

■smarty
{$number|string_format:"%05d"}

■mysql
select lpad(number, 5, '0') from table;

select to_char(number, '00000') from table;

■javascript

var number = 5;
alert(("0"+number).slice(-2));
> 05
alert(("00"+number).slice(-3));
> 005




他にもいろいろやり方はありますが、とりあえずよく使うものはこんなところだと思います。

2010年11月23日火曜日

Smartyでforeachループをネストする

よくやり方を忘れるので備忘録として。

こんな感じの配列を使います。

Array
(
[array1] => Array
(
[0] => Array
(
[id] => 3
[name] => さん
)

[1] => Array
(
[id] => 4
[name] => よん
)

[2] => Array
(
[id] => 5
[name] => ご
)
)
[array2] => Array
(
[0] => Array
(
[id] => 9
[name] => きゅう
)
[1] => Array
(
[id] => 10
[name] => じゅう
)
)
)


テンプレートはこんな感じで記述。

{foreach from=$alllist item="list1" name="list1"}
<ul>
{foreach from=$list1 item="list2" name="list2"}
<li id="{$list2.id}">{$list2.name}</li>
{/foreach}
</ul>
{/foreach}

2006年3月10日金曜日

Smartyのアウトプットフィルタを使ってみる

ウェブサイト(UTF-8)の登録フォームを携帯端末(SJIS)にも対応させるのをやろうと思い、Smartyのアウトプットフィルタを使ってみた。

こんな感じ
$smarty->register_outputfilter("filterSjis");
function filterSjis($buff, &$smarty)
{
return mb_convert_encoding($buff,"SJIS","UTF-8");
}


プリフィルタとポストフィルタはテンプレートに記述されている文字列を変換するだけで、DBなどから動的に出力する文字列には効かない。アウトプットフィルタの場合はブラウザへ出力する直前のデータをフィルタしてくれる。

これで無事解決。。。。と思ったのだけれど、このままでは出力されるヘッダがUTF-8のままのため、文字化けが発生してしまう。さて、どうしたもんか、、、と思いつつGoogleで調べてみたら「ini_set("default_charset", "Shift_JIS");」を入れれば解決できることがわかった。

これが最終形
$smarty->register_outputfilter("filterSjis");
ini_set("default_charset", "Shift_JIS");
function filterSjis($buff, &$smarty)
{
return mb_convert_encoding($buff,"SJIS","UTF-8");
}

2005年8月21日日曜日

SmartyでSJISのテンプレートを使う

「Smarty SJIS」でググるといくつか有益な情報が引っかかるので、それを見て簡単に対応できました。
もっとも、途中でSmartyとは1%も関係ないところでつまづいてしまって無駄に時間を使ってしまったのですが。。。
下記の例だと、plugins_dirにprefilter.pre01.phpとpostfilter.post01.phpのファイルを設置。autoload_filtersを使って自動でフィルタがかかるようにしています。
本体

require("/path/to/smarty");
$smarty = new Smarty;
$smarty->template_dir = "/path/to/template_dir";
$smarty->compile_dir = "/path/to/compile_dir";
$smarty->plugins_dir = "/path/to/plugins_dir";
$smarty->cache_dir = "/path/to/cache_dir";
$smarty->autoload_filters = array('pre' => array('pre01'), 'post' => array('post01'));
$smarty->display("/path/to/template.tpl");


prefilter.pre01.php
<?php
function smarty_prefilter_pre01($buff, &$smarty)
{
return mb_convert_encoding($buff,"EUC-JP","SJIS");
}
?>


postfilter.post01.php
<?php
function smarty_postfilter_post01($buff, &$smarty)
{
return mb_convert_encoding($buff,"SJIS","EUC-JP");
}
?>