[轉貼]PHP: 完美實現ASP.NET MasterPage的方法

[轉貼]PHP: 完美實現ASP.NET MasterPage的方法

ASP.NET中的MasterPage實在是太好用了,而在PHP裏面如果只是用傳統的方法,那麼只能夠把主要版面分段,然後個別使用include()的方式將主要版面湊出來,總覺得說不出來的彆扭。而且如果切割不好,那麼主要版面一旦改版,那麼內容頁就會改到死。使用傳統方法的程式碼大概像這樣:
<body>
<div><?php include('menu.php');?></div>
<div><?php include($page_content);?></div>
<div><?php include('footer.php');?></div>
</body>
如果沒有想過這個問題,也不會去找網路資源,原來早就有人找到方法了。主板頁面就是很一般的頁面,主要用了兩個變數$pagetitle和$pagemaincontent,看名字就知道是頁面標題和主要內容。
<?php
define('app_root',$_SERVER['DOCUMENT_ROOT']);
require_once(app_root."/shared/opendb.inc");
?>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title><?php echo $pagetitle ?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="./style/globalreset.css" rel="stylesheet" media="screen" type="text/css" />
<link href="./style/layout.css" rel="stylesheet" media="screen" type="text/css" />
</head>
<body>
<div id="page">
<div id="header">
<div id="title">
<h1><a href="./index.php"><img src='./images/logo_full.jpg' height='50' /></a></h1>
</div>
<div id="cart">
<?php //require_once(app_root."/shared/login.inc"); ?>
</div>
</div>
<div id="wrapper">
<div id="sidebar">
<div id="menubox">
<?php //require_once(app_root."/shared/navigation.inc"); ?>
</div>
</div>
<div id="mainbox">
<div id="mainarea">
<?php echo $pagemaincontent; ?>
</div>
</div>
</div>
<div id="footer">
</div>
</div>
</body>
</html>
而內容頁面只要定義$pagetitle就好了,完整頁面的輸出就請看注解的部份。雖然這樣子做可能會小小的造成伺服器的負擔,但是跟維護比較起來,這一點點的負擔是絕對值得的。
<?php
define('app_root',$_SERVER['DOCUMENT_ROOT']);
require_once(app_root."/shared/opendb.inc");
$pagetitle = "頁面標題";
//將整個頁面輸出放到緩衝區
ob_start();
?>
頁面內容,隨便你輸出
<?php
//將緩衝區的內容放到變數裏面,然後清除緩衝區
$pagemaincontent = ob_get_contents();
ob_end_clean();
//套用主板頁面
include(app_root."/shared/master.php");
?>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *