Pequeno sistema de templates para PHP5
FIXME Falta uma explicação do código e mais algumas informações sobre as funções.
class Template {
private $template;
private $buffer = array();
function __construct($template, $items){
$this->template = $template;
foreach($items as $k => $v) $this->buffer[(is_numeric($k) ? $v : $k)] = (is_numeric($k) ? '' : $v);
}
public function change($k, $v){
$this->buffer[$k] = $v;
}
public function add($k, $v){
$this->buffer[$k] .= $v;
}
public function generate(&$destiny = ''){
foreach($this->buffer as $k => $v)
$this->template = str_replace('<!-- '.$k.' -->', $v, $this->template);
return ($destiny = $this->template);
}
}
Como usar
<?php
include "lib/template_class.php";
$x = new Template(file_get_contents("index-blank.html"), array('head', 'head title', 'software name', 'software quick info', 'software navigation links'));
$x->change('head', '<script>alert("woot!");</script>');
$x->change('software name', 'lulzware');
$x->change('software quick info', 'oi?');
echo $x->generate();
Ficheiro index-blank.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css" media="screen">
<title><!-- head title --></title>
<!-- head -->
</head>
<body>
<h1><!-- software name --></h1>
<h2><!-- software quick info --></h2>
<ul id="navigation">
<li><a href="#" title="About"><span>About</span></a></li>
<!-- software navigation links -->
</ul>
<div id="side-col">
<ul id="services">
<li style="background: url('images/web-design.png') no-repeat 10px 17px;"><a href="#" title="Some title">Header 1</a><br>
Some description here</li>
</ul>
<!--<h3>
New Header</h3>
<p>
Some info here
</p>
<p id="quote-link">
<a href="#" title="Some title">Learn More...</a>
</p>-->
</div>
<div id="main-content">
<div id="welcome">
<h3>Operação realizada com sucesso!</h3>
<p>
Some info
</p>
</div>
<!-- main -->
<p id="footer">
Copyright © 2007 <a href="http://www.zymic.com/free-templates/">Free Templates</a> by <a href="http://www.zymic.com">Zymic</a> - <a href="http://www.zymic.com/free-web-hosting/">Free Web Hosting</a> - Best Viewed in <a href="http://www.mozillafirefox.us">Mozilla Firefox</a>
</p>
</div>
</body>
</html>