跳轉至內容

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>


華夏公益教科書