您当前的位置: 首页 > 网站编程 > PHP教程 > PHP中获得$Smarty.capture.name截获的输出

PHP中获得$Smarty.capture.name截获的输出

作者:不详 来源:网络 发布时间: 2014-08-23 20:39 点击:
想要获得$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("St

PHP中获得$Smarty.capture.name截获的输出

  想要获得$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 //主页,此页中分需静态部分及动态输出部分

  <?PHP

  if(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变量以便操作
分享到:
本文"PHP中获得$Smarty.capture.name截获的输出"由远航站长收集整理而来,仅供大家学习与参考使用。更多网站制作教程尽在远航站长站。
顶一下
(0)
0%
踩一下
(0)
0%
[点击 次] [返回上一页] [打印]
发表评论
请自觉遵守互联网相关的政策法规,严禁发布色情、暴力、反动的言论。
评价:
表情:
用户名: 密码: 验证码:
关于本站 - 联系我们 - 网站声明 - 友情连接- 网站地图 - 站点地图 - 返回顶部
Copyright © 2007-2013 www.yhzhan.com(远航站长). All Rights Reserved .
远航站长:为中小站长提供最佳的学习与交流平台,提供网页制作与网站编程等各类网站制作教程.
官方QQ:445490277 网站群:26680406 网站备案号:豫ICP备07500620号-4