Skip to content

smarty局部缓存技术

2009 十二月 14
by 荒野无灯

其实我以前只是听过smarty的大名,并没有使用之。
最近做一个叫BlogShow的程序,想到用smarty来实现代码与表现的分离。于是慢慢边学边用,对它有了一定的了解。
发现smrty 是如此强大与神奇的一个东东,使我对它的好感不亚于对TP.
由于我默认是开启smarty的缓存的,但是在些地方的数据是实时更新或者更新较快的,不宜缓存,这样,局部缓存便有用武之地了。
1,insert 法
定义一个函数显示时间的:

1
2
3
4
5
function insert_get_current_time(){
    $timestamp=empty($timestamp)?time():$timestamp;
    $timeoffset=(int) '+8';
    return $ret=gmdate("Y-n-j g:ia", $timestamp + $timeoffset * 3600);
}

然后在模板中:

1
{insert name="get_current_time"}

这样每次打开页面,显示的都是即时时间,而不是缓存的。注意这里的函数名一定要以insert开头,模板中的name与之对应。
这种方法简单,但是如果要显示的内容是一大块的,就不宜使用了。

2,动态block 法

1
2
3
4
5
6
//部分缓存
function smarty_block_nocache($param, $content, $smarty)
 {
    return $content;
}
$smarty->register_block('nocache', 'smarty_block_nocache', false);

在模板中:

1
2
3
{nocache}
{$smarty.now}
{/nocache}

smarty_partly_cache

这样每次刷新页面,显示的时间都是不同的。

3,插件block 法
在Smarty/plugins目录下建一个文件
block.nocache.php 内容如下:

1
2
3
4
5
6
<?php
function smarty_block_nocache($param, $content, $smarty)
{
      return $content;
}  
?>

这样做与方法2的效果是一样的,模板中标签也一样。在 php文件中就不必要再register_block了,很方便。

喜欢这篇文章吗?

请订阅本站 RSS feed填写您的邮件地址,订阅我们的精彩内容:,欢迎点击这里捐赠以支持荒野无灯转播到腾讯微博 转播到腾讯微博

作者:荒野无灯
出处:Hacklog【Hacklog】

声明: 本站遵循 署名-非商业性使用-相同方式共享 3.0 共享协议. 转载请注明转自Hacklog【荒野无灯weblog】

本文链接: http://ihacklog.com/?p=3396

One Response Post a comment
  1. 一月 4, 2010

    因为近来忙于联盟工作,很久不来了,希望谅解,送去新年迟到的祝福,新年快乐!对了,联盟升级改版了,麻烦去联盟重新确认一下您的博客数据。

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <q cite=""> <strong>

 :wink:  :-|  :-x  :twisted:  :)  8-O  :(  :roll:  :-P  :oops:  :-o  :mrgreen:  :lol:  :idea:  :-D  :evil:  :cry:  8)  :arrow:  :-?  :?:  :!:

Note: You may use basic HTML in your comments. Your email address will not be published.

Subscribe to this comment feed via RSS