2011-12-20 49 views
0

我已經緩存啓用我的Smarty的安裝,並有以下模板函數分配值

function smarty_updatedhour($params, $smarty) 
{ 
    $date1 = new DateTime($params['timestamp']); 
    $date2 = new DateTime("now"); 
    $interval = $date1->diff($date2); 
    $smarty->assign("updated_period", $interval->format('%h'), true); 
} 

我已經註冊的插件爲:

$smarty->registerPlugin('function', 'updated_hour', 'smarty_updatedhour', false, array('timestamp')); 

我試圖測試它是否是是否工作

{updated_hour timestamp=$timestamp_vale} 
{$updated_period} 
{if $updated_period > 10} 
    // do other stuffs 
{/if} 

但它不起作用,但是當我禁用smarty頁面緩存時, 有用。

誰能告訴我是什麼問題?

回答

0

在Smarty3你的插件與模板,不是Smarty對象工作。所以你的功能的足跡是function smarty_updatehour(array $params, Smarty_Internal_Template $template)。但這不是你的問題。即使是@sudhir的assignGlobal()提示也無濟於事。

您的非緩存插件不能分配變量,但返回實際輸出:

function smarty_updatedhour($params, $smarty) 
{ 
    $date1 = new DateTime($params['timestamp']); 
    $date2 = new DateTime("now"); 
    $interval = $date1->diff($date2); 
    return $interval->format('%h'); 
} 

,這是因爲{$ updated_period}不是非緩存。該輸出被評估爲一次,然後寫入緩存。試試{nocache}{$updated_period}{/nocache}或者使用上面修改的插件代碼。

+0

好吧,我無法返回函數輸出。這是因爲使用{if} {/ if}在模板上對指定的值進行了進一步處理,並且實際中指定的值不用於在模板內顯示。因此,從您的建議,唯一的可能性是在{nocache}中包裝我的變量輸出(用於測試)或{if}條件。另請注意,我在插件上分配updated_period的同時將nocache設置爲true。 – Prakash 2011-12-20 17:40:57

0

嘗試使用assignGlobal,如:

 
$smarty->assignGlobal("updated_period", $interval->format('%h'), true); 

希望它爲你工作

+0

不,這也是行不通的。 – Prakash 2011-12-20 17:45:06