Implement a simple template engine yourself: Aspects of PHP logic and the separation of the page
Template class:
<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >
Page to call:
<?php
include "mytpl.class.php";
$TPL = new Mytpl ("./templates/", "./templates_c");
Program Simple way
$title = "This is a text title, get from the database";
$content = "This is content";
$tpl->assign ("title", $title);
$tpl->assign ("content", $content);
$tpl->display ("mysmarty.html");
? >
Convert page:
<?php header ("Contenttype=text/html;charset=utf-8");
Class mytpl{private $template _dir;
Private $compile _dir;
Private $tpl _vars=array (); /** * Template path and compiled path * @param template path $template _dir * @param compile path $compile _dir/function __construct ($template _ Dir= "./templates", $compile _dir= "./templates_c") {//Add final/$this->template_dir = RTrim ($template _dir, "/"). '
/'; $this->compile_dir = RTrim ($compile _dir, "/"). '
/';; /** * input variable into array * @param unknown_type $tpl _var * @param unknown_type $value/Public Function assign ($tpl _var, $value =null)
{if ($tpl _var!= "") {$this->tpl_vars[$tpl _var]= $value; /** * Displays the last generated file * @param template file $fileName/Public function display ($fileName) {//template file $tplfile =
$this->template_dir. $fileName;
if (!file_exists ($tplfile)) {return false; //compile filename $confileName = $this->compile_dir. " Com_ ". $fileName.".
PHP "; if (!file_exists ($confileName) | | filemtimE ($confileName) <filemtime ($tplfile)) {$repContent = $this->tpl_replace (file_get_contents ($tplfile));
File_put_contents ($confileName, $repContent);
}//display output include $confileName; /** * Replace template return * Enter description here ... * @param unknown_type $content/Private Function Tpl_replac
E ($content) {//matching regular expression $pattern = Array ('/\<{\s*\$ ([a-za-z_\x7f-\xff][a-za-z0-9_\x7f-\xff]*) \s*\}\>/i ');
$replacement = Array (' <?php echo $this->tpl_vars[' ${1} ';?> ');
$repContent = Preg_replace ($pattern, $replacement, $content);
return $repContent;
}}?>