在PHP上使用模板
我为我的网站创建了一个模板文件…就像:
<!-- template.php --> <?php function showheader() { ?> <head><body> <!-- some of style files and menus --> <div class="content"> <?php } ?> <?php function showfooter() { ?> </div></body></html> <?php } ?> 我使用这个文件作为这样的模板: <?php include_once("template.php"); showheader(); ?> content text or photo or ... etc. <?php showfooter(); ?> 这就是全部…但如果我尝试在模板文件上使用连接,那就搞砸了! <?php // // include_once connection file // query strings goes here // do { echo $row_table['id']; //example } while ($row_table = mysql_fetch_assoc($table)); ?> 我使用这个文件作为include_once(“filename.php”);在模板文件上…此时它会出错…就像这个连接变量是什么,这个连接字符串是什么……等等它无法到达连接字符串…… 顺便说一句,我使用另一个外部连接,如: <?php global $hostname_conn,$database_conn,$username_conn,$password_conn,$conn; $hostname_conn = "localhost"; $database_conn = "test"; $username_conn = "****"; $password_conn = "****"; $conn = mysql_pconnect($hostname_conn,$password_conn) or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("SET NAMES 'utf8'"); ?> 我要哭了!问题是什么……你知道另一种使用模板的方法吗? PS:我将conn.php上的变量更改为全局(并且它没有工作),我更改include,include_once,require,require_once,其中我包含文件,但它没有给出任何东西. 解决方法
这将页面分成两个PHP文件:(1)第一个获取数据,(2)第二个显示数据.
在获取数据时,不应打印出单个字符. 一旦获得所有数据而没有错误 – 是时候包含模板了.该模板还有两个PHP文件:页面本身的模板以及站点中所有页面共同共享的模板. 通过这种方式对事物进行分类,您将解决所有现在和将来的模板问题. 典型的脚本可能看起来像 <? //include our settings,connect to database etc. include dirname($_SERVER['DOCUMENT_ROOT']).'/cfg/settings.php'; //getting required data $DATA=dbgetarr("SELECT * FROM links"); $pagetitle = "Links to friend sites"; //etc //and then call a template: $tpl = "links.php"; include "template.php"; ?> 其中template.php是您的主要网站模板,包括常见部分,如页眉,页脚,菜单等: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>My site. <?=$pagetitle?></title> </head> <body> <div id="page"> <? include $tpl ?> </div> </body> </html> 和links.php是实际的页面模板: <h2><?=$pagetitle?></h2> <ul> <? foreach($DATA as $row): ?> <li><a href="<?=$row['link']?>" target="_blank"><?=$row['name']?></a></li> <? endforeach ?> <ul> 简单,清洁和可维护. settings.php包含所有常用设置: <?php $hostname_conn,$conn; $hostname_conn = "localhost"; $database_conn = "test"; $username_conn = "****"; $password_conn = "****"; $conn = mysql_connect($hostname_conn,$password_conn) or trigger_error(mysql_error(),E_USER_ERROR); mysql_query("SET NAMES 'utf8'") or trigger_error(mysql_error(),E_USER_ERROR); $tpl = "default.php"; $pagetitle = ""; function dbgetarr(){ $a = array(); $args = func_get_args(); $query = array_shift($args); $query = str_replace("%s","'%s'",$query); foreach ($args as $key => $val) { $args[$key] = mysql_real_escape_string($val); } $query = vsprintf($query,$args); $res = mysql_query($query); if (!$res) { trigger_error("dbget: ".mysql_error()." in ".$query); } else { while($row = mysql_fetch_assoc($res)) $a[]=$row; } return $a; } ?> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |