跳至內容

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>


華夏公益教科書