ada banyak templating engine yang bisa digunakan, salah satunya yang terkenal adalah
Smarty. Jika ingin yang sederhana bisa saja gunakan yang seperti:
//file template.php
<?php
class Template {
public $template;
protected $data = array();
function addData($key, $data){
if(is_file($data)){
ob_start();
include $data;
$this->data[$key] = ob_get_contents();
ob_end_clean();
}else{
$this->data[$key] = $data;
}
}
function render(){
if(!$this->template){
return false;
}
include $this->template;
}
function __get($name){
if(array_key_exists($name, $this->data)){
return $this->data[$name];
}
return '';
}
}
?>
file layout.php
<html>
<head>
<title><?php echo $this->title?></title>
</head>
<body>
<div class="header">This is header</div>
<div class="content"><?php echo $this->content?></div>
<div class="footer">
copyright © website name
</div>
</body>
</html>
file form.php
<form name="form1" action="" method="post">
Name: <input type="text" name="name"/>
Email: <input type="text" name="email"/>
Address: <textarea name="address"></textarea>
<input type="submit" value="Save"/>
</form>
file add_user.php : implementasi template
<?php
include template.php
$template = new Template();
$template->template = 'layout.php';
$template->addData('title', 'Add New User');
$template->addData('content', 'form.php');
$template->render();
?>