想要获得$smarty->display后的输出,并作为字符串赋给php变量有两种方法:
1、ob_start
ob_start();
$smarty->display("StockNews/getLeft.tpl");
$string = ob_get_contents();
ob_end_clean();
2、$smarty->_smarty_vars['capture']['captureName'];
$smarty->display("StockNews/getLeft.tpl");
$string = $smarty->_smarty_vars['capture']['captureName'];
//captureName为{capture name=banner}中的name;
//方法需在tpl中使用capture捕获输出
//和第一种原理是一样的,查看编译的php的到:
//php $this->_smarty_vars['capture']['captureName'] = ob_get_contents(); ob_end_clean(); ?>
//不难看出smarty的capture正是使用了php的ob_start方法
总结:这个技巧在部分静态化页面中很有用处。也就是说,当使用了smarty,而且某页面需一部分静态,一部分动态输出时,可以利用上述方法。
我在smarty中静态页面时,采用这种方法:
--static.html
--index.php
--includeStatic.tpl
--index.tpl
--needStatic.tpl
index.php //主页,此页中分需静态部分及动态输出部分
<?PHPif(file_exists('static.html')){//存在静态页输出静态页//使用capture截获包含静态页后的输出$smarty->assign('filename','static.html');$smarty->display('includeStatic.tpl');//动态输出部分$num = rand(1,9);$smarty->assign('num',$num );//再次display,输出index$smarty->display('index.tpl');}else{//不存在静态页往下继续运行,并生成静态页//这里使用上述方法,动态获得需静态部分的输出,这里使用的方法一,同样也可以使用方法二ob_start();//假如要静态数组$array在display后的输出$smarty->assign('array',$array);$smarty->display("needStatic.tpl");//将动态输出内容存至$string变量$string = ob_get_contents();ob_end_clean();//生成静态页$handle = fopen('static.html','wb');fwrite($handle,$string);fclose($handle);//动态输出部分$num = rand(1,9);$smarty->assign('num',$num );//输出index$smarty->display('index.tpl');}?>static.html //此页是主页中静态部分产生的静态页
我是静态页!
includeStatic.tpl //假如存在静态页,则通过display此页截获一个输出(用在index中的)
{capture name=staticed}
{include file=$filename}
{/capture}
needStatic.tpl //没有已静态好的页面时,动态生成静态页,此处为主页静态部分的tpl
{capture name=staticed}
{section name=a loop=$array}
{$array[a]}
{/section}
{/capture}
index.tpl //首页输出,包括静态及动态部分。注:无论静态html是否存在,都会通过capture截获输出,用在此页。
我是首页
这里是静态部分:
{$smarty.capture.staticed}
这里是动态部分:
{$num}
当不愿在php中使用界定符或直接输出html标记时(这样显得代码很乱=.=!),可以通过上述两种方法将display后的html赋给一个php变量以便操作