现在php的项目,动不动就smarty。甚至有的朋友做个两三个页面的新闻系统,也要用smarty。今天按捺不做,谢谢我的看法。本文原文地址为:http://www.miaoqiyuan.cn/p/template-thinks,希望转贴的朋友留一个我的链接。
做个新闻系统,不用smarty,10KB以内的代码搞定,如果用smarty后,就要几百KB了。有些人可能会说不用模板,修改的时候不方便,或则需要每篇文章使用不同的模板,直接用php代码,就不好控制了,在这里给我大家分享一套另类的模板方法。

01 <?php
02   #init.php
03   #获取皮肤设置,如果不存在,则调用default.php
04  $skin = trim($_GET['skin']);
05   if(!isset($skin) || @$skin==''){
06     $skin = 'skin/default.php';
07   }else{
08     $skin = 'skin/'.$skin.'.php';
09     if(!is_file($skin)){
10       $skin = 'skin/default.php';
11     }
12   }
13 ?>

数据处理文件

01 <?php
02    include("inc/init.php");
03    #其他数据处理,把所有的数据,用变量或数组保存
04   ...
05    $title = "1111";
06    $newlist = Array(
07      Array("111"),
08      Array("222"),
09      Array("333")
10    );
11    #引用模板文件
12   require($skin);
13 ?>

模板文件:default.php

01 <html>
02 <head>
03 <meta http-equiv=content-type content="text/html; charset=utf-8">
04 <title><?php echo $title?></title>
05 </head>
06 <body>
07 <?php foreach($newslist as $id => $item){?>
08 <li><?php echo $item['title'];?></li>
09 <?php }?>
10 </body>
11 </html>
12 ?>

模板文件:skin2.php

01 <html>
02 <head>
03 <meta http-equiv=content-type content="text/html; charset=utf-8">
04 <title><?php echo $title?></title>
05 </head>
06 <body>
07 <table>
08 <?php foreach($newslist as $id => $item){?>
09 <tr><td><?php echo $item['title'];?></td></tr>
10 <?php }?>
11 </table>
12 </body>
13 </html>
14 ?>