您的位置:首页 > 其它

80前的前辈,你们都做了些什么?!(五)

2008-01-03 10:40 260 查看
class template {
 var $vars;
 function template() {
  $this->vars = array();
 }
 function render($content_template, $page_title, $wrap_file = '', $nowrap = false) {
  error_reporting(E_ALL ^ E_NOTICE); // Clobber notices in template output
  extract($this->vars);
  $path = defined('TEMPLATE_PATH')
  ? './templates/'.THEME.'/'.TEMPLATE_PATH.'/'
  : './templates/'.THEME.'/';
  include($nowrap ? $path.$content_template : ($wrap_file ? $path.$wrap_file : $path.'wrap.html'));
 }
 
 function fetch($content_template) {
  ob_start();
  $this->render($content_template, '', '', true);
  $rettext = ob_get_contents();
  ob_end_clean();
  return $rettext;
 }
  
 function assign($var, $value = '') {
  if (is_array($var)) {
   foreach ($var as $k => $v) {
    $this->vars[$k] = $v;
   }
  } else {
   $this->vars[$var] = $value;
  }
 }
}
$t = new template();
这是一个模板的类,是PHP写的,那么模板该如何写呢?答案还是PHP,在你的模板html文件中
使用这样的方法,把assign的变量显示出来。当然如果你要用循环或者各种复杂的
结构,各种复杂的字符串函数都可以自由的调用。试问还有什么模板语言能比PHP还强大呢?
 
把上面的类放到include里面,然后需要用到模板的文件就包含这个include,下面我们看看几个主要的用法
1 实现基本的模板功能
变量赋值,这里可以是变量,也可以是数组
$t->assign($_POST);  
  $t->assign('error', $error);
 
 $t->render('test.html', "Title","",true);
2 实现页面布局
例如有一个布局页面,wrap.html
那么上面的render就要改成 $t->render('test.html', "Title");
这样它就默认使用wrap.html最为布局,而test.html只是这个布局中间的一个小块
3实现类似局部模板生成的例子
假设网页中有一个Block是testfetch.php,它对应一个testfetch.html的模板,那么
这两个文件可以这样写:
testfetch.php

include 'include.php';
$t->assign('error', "Error Message");
echo $t->fetch('testfetch.html');
?>
testfetch.html
    
           
   

  
这样你就可以在其它任何地方包含这个Block。
 
总结:其实所有的语言JSP等等,都可以使用这样的模板来构建,其实JSP,PHP本身就是最好的教本语言,
为什么还要去学习我们不熟悉的Smarty,Velocity等等。其实结果都是一样的。
本模板类出自PHPBT.

Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=611294
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: