Get Smarty

Donate

Paypal

Smarty Icon

You may use the Smarty logo according to the trademark notice.

Smarty Template Engine Smarty Template Engine

For sponsorship, advertising, news or other inquiries, contact us at:

Sites Using Smarty

Advertisement

キャッシュ可能なプラグインの出力の制御

Smarty 2.6.0 から、プラグインを登録する際にキャッシュ可能なプラグインを宣言する事が出来ます。 register_block() register_compiler_function() および register_function() の第3パラメータは $cacheable と呼ばれ、デフォルトは TRUE です。この時、Smarty 2.6.0 以前のプラグインの振る舞いになります。

$cacheable=false であるプラグインが登録された時、 プラグインはページがキャッシュから読まれる場合でもページを表示する度に呼ばれます。 プラグイン関数は {insert} 関数に少し似た振る舞いをします。

{insert} とは対照的に、プラグインの属性はデフォルトではキャッシュされません。 キャッシュするためには第4パラメータ $cache_attrs によって宣言します。$cache_attrs はキャッシュされるべき属性の名前を格納した配列であり、 プラグイン関数はページがキャッシュから取り出される度に 属性はキャッシュに記述されていたものとして値を取得します。

Example 14.10. プラグインの出力がキャッシュされるのを防ぐ


<?php
$smarty->caching = true;

function remaining_seconds($params, &$smarty) {
    $remain = $params['endtime'] - time();
    if($remain >= 0){
        return $remain . ' second(s)';
    }else{
        return 'done';
    }
}

$smarty->register_function('remaining', 'remaining_seconds', false, array('endtime'));

if (!$smarty->is_cached('index.tpl')) {
    // データベースから $obj を取り出して割り当てる
    $smarty->assign_by_ref('obj', $obj);
}

$smarty->display('index.tpl');
?>

   

index.tpl は次のようになります。


Time Remaining: {remaining endtime=$obj->endtime}

   

たとえページがキャッシュされていても $obj の endtime の秒数までは各ページの表示は変更されていきます。 その後のリクエストでページがキャッシュに書かれている時、 endtime 属性がキャッシュされたのでオブジェクトをデータベースから取り出す必要があるだけです。


Example 14.11. テンプレートの一節がキャッシュされるのを防ぐ


index.php:

<?php
$smarty->caching = 1;

function smarty_block_dynamic($param, $content, &$smarty) {
    return $content;
}
$smarty->register_block('dynamic', 'smarty_block_dynamic', false);

$smarty->display('index.tpl');
?>

   

index.tpl は次のようになります。


Page created: {'0'|date_format:'%D %H:%M:%S'}

{dynamic}

Now is: {'0'|date_format:'%D %H:%M:%S'}

... 他にも何か ...

{/dynamic}

   

ページをリロードした時に、両方の日付が異なる点に注意して下さい。 一つは dynamic であり、もう一つは static です。 {dynamic}...{/dynamic} 間に含まれるコンテンツ全てを動的に生成する事ができ、 残るコンテンツはキャッシュされない事を確認して下さい。

Comments
No comments for this page.

Advertisement

Sponsors [info]

Sponsors