An Easy-to-use template class.

Source: Internet
Author: User
Tags define array empty end variables php class php code variable
Template PHP Code:--------------------------------------------------------------------------------

<?php
if (!defined ("__template_h_php__")) {
Define ("__template_h_php__", "template.h.php");
/******************** CODE START ********************/

PHP Class Library: template.h.php
Operating Environment: PHP4.0
Modification Date: 2002-08-01
Last modified: Stangly.wrong
Introduction to the Class Library: template extraction Display class
/////////////////////////////////////////////////////////////

Class Name: Template base class Template_base
Function: Template specific operation class.
Class Template_base {
var $classname = "Template_base";

/* If set, echo assignments * *
var $debug = false;

/* $file [handle] = "filename"; */
var $file = array ();

/* Relative filenames are relative to this pathname * *
var $root = "";

/* $varkeys [key] = "key"; $varvals [Key] = "value"; */
var $varkeys = array ();
var $varvals = array ();

/* "Remove" => remove undefined variables
* "comment" => replace undefined variables with comments
* "Keep" => keep undefined variables
*/
var $unknowns = "Remove";

* * "yes" => Halt, "" "=> the" ", Continue," no "=> ignore error quietly * *
var $halt _on_error = "yes";

/* Last error message was retained here/*
var $last _error = "";


/***************************************************************************/
/* Public:constructor.
* Root:template directory.
* Unknowns:how to handle unknown variables.
*/
function template_base ($root = ".", $unknowns = "Remove") {
$this->set_root ($root);
$this->set_unknowns ($unknowns);
}

/* Public:setroot (pathname $root)
* Root:new Template directory.
*/
function Set_root ($root) {
if (!is_dir ($root)) {
$this->halt ("Set_root: $root is not a directory.");
return false;
}

$this->root = $root;
return true;
}

/* Public:set_unknowns (enum $unknowns)
* Unknowns: "Remove", "comment", "keep"
*
*/
function set_unknowns ($unknowns = "Keep") {
$this->unknowns = $unknowns;
}

/* Public:set_file (array $filelist)
* Filelist:array of handle, filename pairs.
*
* Public:set_file (String $handle, String $filename)
* Handle:handle for a filename,
* Filename:name of template file
*/
function Set_file ($handle, $filename = "") {
if (!is_array ($handle)) {
if ($filename = = "") {
$this->halt ("set_file:for handle $handle filename is empty.");
return false;
}
$this->file[$handle] = $this->filename ($filename);
} else {
Reset ($handle);
while (the list ($h, $f) = each ($handle)) {
$this->file[$h] = $this->filename ($f);
}
}
}

/* Public:set_block (String $parent, String $handle, String $name = "")
* Extract the template $handle from $parent,
* Place variable {$name} instead.
*/
function Set_block ($parent, $handle, $name = "") {
if (! $this->loadfile ($parent)) {
$this->halt ("Subst:unable to load $parent.");
return false;
}
if ($name = = "")
$name = $handle;

$str = $this->get_var ($parent);
$reg = "/<!--s+begin $handles +--> (. *) \ns*<!--s+end $handles +-->/sm";
Preg_match_all ($reg, $str, $m);
$str = Preg_replace ($reg, "{".) $name} ", $STR);
$this->set_var ($handle, $m [1][0]);
$this->set_var ($parent, $STR);
}

/* Public:set_var (array $values)
* Values:array of variable name, value pairs.
*
* Public:set_var (String $varname, String $value)
* Varname:name of a variable which is defined
* Value:value of that variable
*/
function Set_var ($varname, $value = "") {
if (!is_array ($varname)) {
if (!empty ($varname))
if ($this->debug) echo "Scalar:set * $varname * to * $value *<br>\n";
$this->varkeys[$varname] = "/". $this->varname ($varname). " /";
$this->varvals[$varname] = $value;
} else {
Reset ($varname);
while (the list ($k, $v) = each ($varname)) {
if (!empty ($k))
if ($this->debug) echo "Array:set * $k * to * $v *<br>\n";
$this->varkeys[$k] = "/". $this->varname ($k). " /";
$this->varvals[$k] = $v;
}
}
}

/* PUBLIC:SUBST (String $handle)
* Handle:handle of template where variables are to be substituted.
*/
function subst ($handle) {
if (! $this->loadfile ($handle)) {
$this->halt ("Subst:unable to load $handle.");
return false;
}

$str = $this->get_var ($handle);
$str = @preg_replace ($this->varkeys, $this->varvals, $STR);
return $str;
}

/* PUBLIC:PSUBST (String $handle)
* Handle:handle of template where variables are to be substituted.
*/
function Psubst ($handle) {
echo $this->subst ($handle);

return false;
}

/* Public:parse (String $target, String $handle, Boolean append)
* Public:parse (string $target, Array $handle, Boolean append)
* Target:handle of variable to generate
* Handle:handle of template to substitute
* Append:append to target handle
*/
Function Parse ($target, $handle, $append = False) {
if (!is_array ($handle)) {
$str = $this->subst ($handle);
if ($append) {
$this->set_var ($target, $this->get_var ($target). $str);
} else {
$this->set_var ($target, $STR);
}
} else {
Reset ($handle);
while (the list ($i, $h) = each ($handle)) {
$str = $this->subst ($h);
$this->set_var ($target, $STR);
}
}

return $str;
}

function Pparse ($target, $handle, $append = False) {
echo $this->parse ($target, $handle, $append);
return false;
}

/* Public:get_vars () * *
function Get_vars () {
Reset ($this->varkeys);
while (the list ($k, $v) = each ($this->varkeys)) {
$result [$k] = $this->varvals[$k];
}

return $result;
}

/* Public:get_var (String varname)
* Varname:name of variable.
*
* Public:get_var (array varname)
* Varname:array of variable names
*/
function Get_var ($varname) {
if (!is_array ($varname)) {
return $this->varvals[$varname];
} else {
Reset ($varname);
while (the list ($k, $v) = each ($varname)) {
$result [$k] = $this->varvals[$k];
}

return $result;
}
}

/* public:get_undefined ($handle)
* Handle:handle of a template.
*/
function get_undefined ($handle) {
if (! $this->loadfile ($handle)) {
$this->halt ("Get_undefined:unable to load $handle.");
return false;
}

Preg_match_all ("/{([^}]+)}/", $this->get_var ($handle), $m);
$m = $m [1];
if (!is_array ($m))
return false;

Reset ($m);
while (the list ($k, $v) = each ($m)) {
if (!isset ($this->varkeys[$v]))
$result [$v] = $v;
}

if (count ($result))
return $result;
Else
return false;
}

/* Public:finish (String $str)
* Str:string to finish.
*/
function Finish ($STR) {
Switch ($this->unknowns) {
Case "Keep":
Break
Case "Remove":
$str = Preg_replace ('/{[^ \t\r\n}]+}/', "", $str);
Break
Case "comment":
$str = Preg_replace ('/{([^ \t\r\n}]+)}/', "<!--Template $handle: Variable \1 undefined-->", $str);
Break
}

return $str;
}

/* PUBLIC:P (String $varname)
* Varname:name of variable to print.
*/
function P ($varname) {
echo $this->finish ($this->get_var ($varname));
}

function Get ($varname) {
return $this->finish ($this->get_var ($varname));
}

/***************************************************************************/
/* Private:filename ($filename)
* Filename:name to be completed.
*/
function filename ($filename) {
if (substr ($filename, 0, 1)!= "/") {
$filename = $this->root. " /". $filename;
}

if (!file_exists ($filename))
$this->halt ("Filename:file $filename does not exist.");

return $filename;
}

/* Private:varname ($varname)
* Varname:name of a replacement variable to be protected.
*/
function VarName ($varname) {
Return Preg_quote ("{". $varname. "}");
}

/* Private:loadfile (String $handle)
* handle:load file defined by handle, if it isn't loaded yet.
*/
function LoadFile ($handle) {
if (Isset ($this->varkeys[$handle]) and!empty ($this->varvals[$handle]))
return true;

if (!isset ($this->file[$handle])) {
$this->halt ("LoadFile: $handle is not a valid handle.");
return false;
}
$filename = $this->file[$handle];

$str = Implode ("", @file ($filename));
if (empty ($STR)) {
$this->halt ("Loadfile:while loading $handle, $filename does not exist or are empty.");
return false;
}

$this->set_var ($handle, $STR);

return true;
}

/***************************************************************************/
/* Public:halt (String $msg)
* Msg:error.
*/
function Halt ($msg) {
$this->last_error = $msg;

if ($this->halt_on_error!= "no")
$this->haltmsg ($msg);

if ($this->halt_on_error = = "Yes")
Die ("<b>Halted.</b>");

return false;
}

/* Public, override:haltmsg ($msg)
* Msg:error.
*/
function Haltmsg ($msg) {
printf ("<b>template error:</b>%s<br>\n", $msg);
}
} #end Template_base Class

Class Name: Template
Features: Template processing extensions
Description: Inherits from Tempalte_base, modifies part of the template handler function
Class Template extends Template_base {
var $handelkey = array ();
var $handelcount;

function Template ($filename) {
$this->template_base ();
if (Empty ($filename) | |!file_exists ($filename)) {
Die ("Template-> Template (): Error-file $filename does not exist");
}
$this->set_file (' ihtml ', $filename);
$this->handelcount = 1;
return true;
}

function Output () {
$this->p (' out ');
return true;
}

function Compile () {
$this->parse (' Out ', ' ihtml ');
return true;
}

function OP () {
$copyright = ' <p align=center>©2002 new Maya workroom</p> ';
$this->setvar (' copyright ', $copyright);
$this->compile ();
$this->output ();
return true;
}

Example:var or array
$key = Array (
' Row1 ' => ' serial number ',
' Row2 ' => ' name ',
' row3 ' => ' sex '
// )
function SetVar ($key, $value = ' ") {
$this->set_var ($key, $value);
return true;
}

$key is define
function Setblock ($blockname) {
$this->handelkey[$blockname] = $this->handelcount;
$this->set_block (' ihtml ', $blockname, $this->handelcount);

$this->handelcount + +;
return true;
}

Example:array
$data = Array (
' 0 ' => array (' 1 ', ' 2 ', ' 3 '),
' 1 ' => Array (' 4 ', ' 5 ', ' 6 '),
// );
or Var
function Setblockvar ($data, $blockname, $var = ') {
if (Is_array ($data)) {
$x = count ($data);
$y = count ($data [0]);

for ($i = 0; $i < $x; $i + +) {
for ($j = 0; $j < $y; $j + +) {
$this->set_var (' var '. $j, $data [$i] [$j]);
}
$this->parse ($this->handelkey[$blockname], $blockname, true);
}
} else {
$this->set_var ($var, $data);
}
return true;
}

function Blockparse ($blockname) {
if (!empty ($blockname)) {
$this->parse ($this->handelkey[$blockname], $blockname, true);
return true;
}
return false;
}

} #end Template Class

/******************** CODE End ********************/
}
?>

--------------------------------------------------------------------------------


The method called
$t = new Template (' Test.tpl ');
$t->setvar (' Test ', ' China ');//replace the related string.
$t->op ();

If you're using a template like this,
<table>
<!--BEGIN list-->
<tr>
<td>{var0}</td>
<td>{var1}</td>
</tr>
<!--end list-->
</table>

<table>
<!--BEGIN List2-->
<tr>
<td>{var0}</td>
<td>{var1}</td>
</tr>
<!--end List2-->
</table>

Then use this
?
Include ("template.h.php");
Include (' template.h.php ');
$data =array ();
$data [' List ']=array (
' 0 ' =>array (' A1 ', ' A2 '),
' 1 ' =>array (' B1 ', ' B2 ')
);
$data [' List2 ']=array (
' 0 ' =>array (' Aa1 ', ' Aa2 '),
' 1 ' =>array (' bb1 ', ' bb2 ')
);
$t = new Template (' Test.tpl ');
$t->setblock (' list ');
$t->setblockvar ($data [' list '], ' list ');
$t->setblock (' List2 ');
$t->setblockvar ($data [' List2 '], ' list2 ');
$t->op ();
?>

Other ways to study it again. If you are interested, you can expand it for me. Oh


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.