facebook twitter hatena line email

Php/Smarty/技術メモ

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

全角カナを半角カナへ変換

Smarty/libs/pluginsに modifier.mbkana.php

<?php
function smarty_modifier_mbkana($string, $char_set = 'UTF-8')
{
  return mb_convert_kana($string, "ka", $char_set);
}
?>

を追加 使い方:{$kana|mbkana:sjis-win}

utf8に変換

Smarty/libs/pluginsに modifier.utf8.php

<?php
function smarty_modifier_utf8($string, $char_set = 'ASCII,JIS,UTF-8,EUC-JP,SJIS')
{
  return mb_convert_encoding($string, 'UTF-8', $char_set);
}
?>

を追加 使い方:{$value|utf8:sjis-win}

便利プラグイン

日本語文字丸め処理(文字列幅制御) mb_strimwidth http://d.hatena.ne.jp/kidd-number5/20060417/1145253097

日本語文字丸め処理(文字数制御) mbtruncate http://tdiary.ishinao.net/20040423.html

キャッシュを使用

$smarty = new Smarty();
// キャッシュ有効設定
$smarty->caching        = 1;
// テンプレートファイルの更新チェックフラグ
$smarty->compile_check  = false;
// キャッシュするディレクトリ設定
$smarty->cache_dir      = dirname(__FILE__) . '/cache/';
// キャッシュの生存時間(秒)を設定
$smarty->cache_lifetime = 600;
if ($smarty->is_cached("index.tpl", $cache_id)) {
    $smarty->assign("random" ,rand());
}
$smarty->display("index.tpl", $cache_id);

キャッシュで部分的に動的動作

*main.tpl
{{insert name="getTest" title="test"}}
*main.php(プラグイン未使用の場合
function insert_getTest($params, &$smarty) {
   $smarty->assign('title', $params['title']);
   return $smarty->fetch('test.tpl');
}
*plugins/insert.getTest.php(プラグイン使用時
function smarty_insert_getTest($params, &$smarty) {
   $smarty->assign('title', $params['title']);
   return $smarty->fetch('test.tpl');
}

一時間以内のキャッシュクリア

$smarty->clear_all_cache(3600);

自作のプラグインを置くDIRを用意

以下のように定義することで自作プラグインDIRを個別に追加できる

$smarty->plugins_dir[] = '/var/www/smarty/plugins';

指定日以降にNEWを付ける

{{if $smarty.now|date_format:'%Y-%m-%d %H:%M:%S'>='2011-11-14 08:30:00'}}New!!{{/if}}
{{if $smarty.now|date_format:'%Y-%m-%d'>='2011-11-14'}}New!!{{/if}}