【问题标题】:assigning value from smarty plugins从 smarty 插件中赋值
【发布时间】:2011-12-20 06:55:04
【问题描述】:

我在我的 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 页面缓存时它不起作用。

谁能告诉我是什么问题?

【问题讨论】:

    标签: smarty smarty3


    【解决方案1】:

    在 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} 或使用上面修改过的插件代码。

    【讨论】:

    • 好吧,我无法返回函数输出。这是因为使用 {if}{/if} 在模板上进一步处理分配的值,而实际分配的值并不意味着在模板中显示。因此,根据您的建议,唯一的可能性是将我的变量输出(用于测试)或 {if} 条件包装在 {nocache} 中。另请注意,在我的插件上分配 updated_period 时,我确实将 nocache 设置为 true。
    【解决方案2】:

    尝试使用assignGlobal,例如:

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

    希望对你有用

    【讨论】:

      猜你喜欢
      • 2011-05-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-28
      • 2015-07-05
      相关资源
      最近更新 更多