這應該爲你工作:
(我把一個視圖註釋來解釋怎麼回事!)
文件結構:
|
| - index.php
| - navigation.php
|
| - templates
| | - page.php
|
| - views
| - skills.php
| - projects.php
的index.php:
<?php
//Error reporting only for testing environment
ini_set("display_errors", 1);
error_reporting(E_ALL);
?>
<?php
//To save some code lines i put that in a function
function getContent($path) {
ob_start();
require_once($path);
$content = ob_get_contents();
ob_end_clean();
return $content;
}
$pageData = new stdClass();
$pageData->title = "Thomas Blom Hansen: Portfolio site";
$pageData->content = getContent("navigation.php");
$pageData->css = "<link href='css/layout.css' rel='stylesheet' />";
if(!empty($_GET['page'])) {
$fileToLoad = $_GET['page'];
$pageData->content .= getContent("views/$fileToLoad.php");
} else {
$fileToLoad = "skills";
$pageData->content .= getContent("views/$fileToLoad.php");
}
$page = getContent("templates/page.php");
$page = str_replace('%%$pageData->title%%', $pageData->title, $page);
$page = str_replace('%%$pageData->css%%', $pageData->css, $page);
$page = str_replace('%%$pageData->content%%', $pageData->content, $page);
echo $page;
?>
navigation.php:
<nav>
<a href='index.php?page=skills'>My skills and background</a>
<a href='index.php?page=projects'>Some projects</a>
</nav>
projects.php:
<h1>Projects I have worked on</h1>
<ul>
<li>Ahem, this will soon be updated</li>
</ul>
模板/ page.php文件:
<!DOCTYPE html>
<html>
<head>
<title>%%$pageData->title%%</title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />
%%$pageData->css%%
</head>
<body>
%%$pageData->content%%
</body>
</html>
的意見/技能。PHP:
<h1>Skills and educational background</h1>
<p>Read all about my skills and my formal training</p>
<?php
echo "test"; //Little example to show that php gets parsed and that's also why the file extension still *.php is
?>
輸出/源代碼是:
<!DOCTYPE html>
<html>
<head>
<title>Thomas Blom Hansen: Portfolio site</title>
<meta http-equiv='Content-Type' content='text/html;charset=utf-8' />
<link href='css/layout.css' rel='stylesheet' />
</head>
<body>
<nav>
<a href='index.php?page=skills'>My skills and background</a>
<a href='index.php?page=projects'>Some projects</a>
</nav>
<h1>Skills and educational background</h1>
<p>Read all about my skills and my formal training</p>
test
</body>
</html>
側面說明:
在這裏,我使用require_once
所以,如果你有一個複雜的網站文件沒有得到多次包括! (請參閱:http://php.net/manual/en/function.require-once.php)
還添加了%%
模板中的php變量之前和之後,這樣就不太可能用這個名稱編寫文本!
非常感謝!但是我很難理解'$ page = str_replace('%% $ pageData-> title %%',$ pageData-> title,$ page);'在做什麼。 –
@PrithvishBaidya歡迎您!你不明白什麼? – Rizier123
我也遇到了getContent函數的問題。你能解釋一下'ob_start()'的含義嗎? –