跳到內容

PHP 程式設計/模板

來自華夏公益教科書,開放的書籍,為開放的世界

基本模板

[編輯 | 編輯原始碼]

在 PHP 中使用模板最簡單的方法對於減少錯誤和節省頁面時間非常有效。首先,確保您的伺服器啟用了 PHP 等。等等,等等。

準備好後,建立一個將作為所有頁面模板的頁面。例如

This is a title at the top of my page

This is the body of my page

This is a copyright notice

現在,假設您想要另外兩個頁面,它們具有相同的頁首和頁尾。您不必再次編寫程式碼。您可以將頁首儲存為一個模板,並將頁尾儲存為另一個模板。只需獲取從頁首 html 到正文文字開始的部分的所有內容

<html><body><p>This is a title at the top of my page</p>

現在將此儲存為單獨的檔案。我喜歡使用副檔名 .inc(頁尾也一樣)

<p>This is the bottom of my page</p></body></html>

現在,在您的主頁面中,只需鍵入

 <?php require('header.inc'); ?>
 <p>this is the body of my page</p>
 <?php require('footer.inc'); ?>

這就是您的頁面。將其儲存為 .php,上傳並檢查。

您還可以使用 include()include_once() 函式,如果頁面應該繼續載入,即使檔案無法包含。

require()include()include_once() 函式將與其他檔案型別一起工作,並且可以在頁面的任何位置使用。

高階:嘗試將此與 if 語句一起使用以進行動態模板化......哦......

管理模板

[編輯 | 編輯原始碼]

管理模板允許您使用模板引擎建立和使用 PHP 模板。PHP 開發人員/設計人員不必建立引擎以供使用。最可靠的 PHP 模板引擎是 Smarty( [1] )。管理模板系統易於使用,並且主要用於大型網站,因為需要動態分頁。MediaWiki 是管理模板系統的示例之一。管理模板對於新使用者和高階使用者都易於使用,例如

  • index.php
 // This script is based on Smarty
 require_once("libs/Smarty.inc.php");
 // Compiled File Directory
 $smarty->compile_dir = "compiled";
 // Template Directory
 $smarty->template_dir = "templates";
 // Assign a Variable
 $smarty->assign("variable","value");
 // Display The Parsed Template
 $smarty->display("template.tpl");
  • template.tpl
The Value of Variable is : {$variable}
  • 輸出
The Value of Variable is : value

自己動手

[編輯 | 編輯原始碼]

模板引擎工作得很好,但是如果您只是在尋找基本的搜尋和替換模板功能,那麼編寫自己的指令碼非常容易。

  • 簡單模板函式
function Template($file, $array) {
	if (file_exists($file)) {
		$output = file_get_contents($file);
		foreach ($array as $key => $val) {
			$replace = '{'.$key.'}';
			$output = str_replace($replace, $val, $output);
		}
		return $output;
	}
}
  • 使用函式
$fruit = 'Watermelon';
$color = 'Gray';

//parse and return template
$Template_Tpl = Template('template.tpl',
	array
	(
		'fruit'	=> $fruit,
		'color'	=> $color
	));

//display template
echo $Template_Tpl;
  • template.tpl,用於上述函式的模板
<p>
  <b>Your Favorite Food Is: {fruit}</b>
  <b>Your Favorite Color Is: {color}</b>
</p>
  • 解析的模板輸出
<p>
  <b>Your Favorite Food Is: Watermelon</b>
  <b>Your Favorite Color Is: Gray</b>
</p>


華夏公益教科書