An easy-to-use template class.

Source: Internet
Author: User
PHP code :--------------------------------------------------------------------------------? Phpif (! Defined (_ TEMPLATE_H_PHP _) {define (_ TEMPLATE_H_PHP __, template. h. PHP code: templates :--------------------------------------------------------------------------------

If (! Defined ("_ TEMPLATE_H_PHP __")){
Define ("_ TEMPLATE_H_PHP _", "template. h. php ");
/******************* Code start ***************** ***/

// PHP class library: template. h. php
// Running environment: PHP4.0
// Modification time:
// Last Modified: stangly. wrong
// Class library introduction: Class displayed for template extraction
//////////////////////////////////////// /////////////////////

// Class name: Template base class Template_base
// Function: Operation class of the template.
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, "report" => report error, continue, "no" => ignore error quietly */
Var $ halt_on_error = "yes ";

/* Last error message is 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 (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 = "/ (. *) \ Ns * /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 that is to be 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 *
\ N ";
$ This-> varkeys [$ varname] = "/". $ this-> varname ($ varname )."/";
$ This-> varvals [$ varname] = $ value;
} Else {
Reset ($ varname );
While (list ($ k, $ v) = each ($ varname )){
If (! Empty ($ k ))
If ($ this-> debug) echo "array: set * $ k * to * $ v *
\ 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 (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 (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 (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 (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}] + )}/'," ", $ 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 is not 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 is empty .");
Return false;
}

$ This-> set_var ($ handle, $ str );

Return true;
}

/*************************************** ************************************/
/* Public: halt (string $ msg)
* Msg: error message to show.
*/
Function halt ($ msg ){
$ This-> last_error = $ msg;

If ($ this-> halt_on_error! = "No ")
$ This-> haltmsg ($ msg );

If ($ this-> halt_on_error = "yes ")
Die (" Halted.");

Return false;
}

/* Public, override: haltmsg ($ msg)
* Msg: error message to show.
*/
Function haltmsg ($ msg ){
Printf (" Template Error:% S
\ N ", $ msg );
}
} # End Template_base class

// Class name: Template
// Function: template processing extension
// Description: it inherits from Tempalte_base and modifies some template processing functions.
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 ='

©2002 new Maya workroom

';
$ This-> SetVar ('copyright', $ copyright );
$ This-> Compile ();
$ This-> OutPut ();
Return true;
}

// Example: var or array
// $ Key = array (
// 'Row1' => 'sequence number ',
// 'Row2' => 'name ',
// 'Row3' => 'gender'
//)
Function SetVar ($ key, $ value = '){
$ This-> set_var ($ key, $ value );
Return true;
}

// $ Key is define the current block
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 ***************** ***/
}
?>

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


Call method
$ T = new template ('test. tpl ');
$ T-> SetVar ('test', 'China'); // replace the relevant string.
$ T-> OP ();

If such a template is used







{Var0} {Var1}









{Var0} {Var1}


Use
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 ();
?>

Let's take a look at other methods. If you are interested, expand it for me. Haha

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.