|
Smarty
WARNING: All discussion is moving to https://reddit.com/r/smarty, please go there! This forum will be closing soon. |
|
View previous topic :: View next topic |
Author |
Message |
pitbull82 Smarty Rookie
Joined: 01 Feb 2006 Posts: 18 Location: Poland
|
Posted: Wed Mar 30, 2011 11:11 am Post subject: Caching in template function doesn't work |
|
|
Hello
I have a few simple files as below.
index.php
Code: | <?php
require ('libs/Smarty.class.php');
$page = new Smarty();
$page->plugins_dir[]='plugins';
$page->display('index.tpl');
?> |
templates/index.tpl
templates/menu.tpl
plugins/function.testfunction.php
Code: | <?php
function smarty_function_testfunction($params, &$template)
{
$template->setCaching(\Smarty::CACHING_LIFETIME_SAVED);
$template->setCacheLifetime(3600);
if (!$template->isCached('menu.tpl')) {
$template->assignGlobal('menu',rand(0,100000));
}
$output = $template->fetch('menu.tpl');
$template->setCaching(\Smarty::CACHING_OFF);
return $output;
}
?>
|
Unfortunately Smarty doesn't create any cache files at all in this situation. If I move code to index.php (with tiny changes to create cache for menu.tpl) it creates cache file correctly. I can suppose this may be related to scope issues (similar thread but not about caching - http://www.smarty.net/forums/viewtopic.php?t=19045 ) b. Does anyone know how to solve it or maybe I'm doing something in wrong way?
Best regards |
|
Back to top |
|
U.Tews Administrator
Joined: 22 Nov 2006 Posts: 5068 Location: Hamburg / Germany
|
Posted: Thu Mar 31, 2011 8:35 pm Post subject: |
|
|
It's again the scoping.
Your $template->setCaching(...) will effect the setting of the template object of index.tpl, not the setting for menu.tpl.
Solution: create an new explicite template object for menu.tpl
Code: | function smarty_function_testfunction($params, &$template)
{
$tpl=$template->createTemplate('menu.tpl');
$tpl->setCaching(Smarty::CACHING_LIFETIME_SAVED);
$tpl->setCacheLifetime(10);
if (!$tpl->isCached()) {
$tpl->assignGlobal('menu',rand(0,100000));
}
$output = $tpl->fetch();
$tpl->setCaching(Smarty::CACHING_OFF);
return $output;
} |
|
|
Back to top |
|
pitbull82 Smarty Rookie
Joined: 01 Feb 2006 Posts: 18 Location: Poland
|
Posted: Sat Apr 02, 2011 6:11 pm Post subject: |
|
|
Thanks a lot. It's working now without any problems |
|
Back to top |
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|