Template, PHPLIB processing method

Source: Internet
Author: User
If you want to know what Templates are, first take a look at the wonderful article "Templates-why and how to use them in PHP3" written by SaschaSchumann. (if you want to know what Templates are, first, let's take a look at the first few paragraphs of the wonderful article "Templates-why and how to use them (Templates-why and how to use them in PHP3) written by Sascha Schumann.

In general, templates allow you to completely separate your PHP code from HTML, which makes HTML graphic designers very happy and prevents them from losing your valuable design.

It's not FastTemplates. Do we really need another article about the template on PHPBuilder? Well, yes, because there are more than one method to implement the template using PHP. Sascha's article describes how to use FastTEmplates, but the PHP Basic Class Library ("PHPLIB") has its own template implementation.

What are their differences? FastTemplates was originally transformed from a Perl library. FastTemplates works well for Perl programs, but is not ideal for PHP. Kristian Koehntopp has compiled the PHPLIB template from scratch. as a pure PHP library, it provides PHP advantages better. One of the advantages is that Kristian's design uses preg_replace () to analyze the template, which is said to be faster than ereg_replace () in FastTemplate. Another benefit of the PHPLIB template is that it allows dynamic block implementations to be nested, unlike FastTemplates.

Both databases have very similar features and capabilities, but if you have already used FastTemplates and want to learn how to use the PHPLIB template, you should forget everything you know about FastTemplates. Their features may be similar, but the PHPLIB template does nothing different than FastTemplates.

Use PHPLIB Template
Let's start with a simple example. Assume that there is a template named MyTemplate under/home/mydir/mytemplates/. it has some text and the content may be:

Congratulations! You won a {some_color} Honda Prelude!

Note that "{some_color}" is surrounded by braces. Braces indicate that some_color is a template variable. We may want to write a script that can load the template, insert the PHP variable $ my_color value in the {some_color} template variable, and then output new text.
If $ my_color happens to be set to "blue", the final output may be:

Congratulations! You win a new blue Honda Prelude!

The following is the PHP script for the above results:

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

Include "template. inc ";

$ My_color = "blue ";
// Will be used later

$ T = new Template ("/home/mydir/mytemplates /");
// Create a template object named $ t

$ T-> set_file ("MyFileHandle", "MyTemplate. ihtml ");
// Set MyFileHandle = our template file

$ T-> set_var ("some_color", $ my_color );
// Set the template variable some_color = $ my_color.

$ T-> parse ("MyOutput", "MyFileHandle ");
// Set the template variable MyOutput = the analyzed file

$ T-> p ("MyOutput ");
// Output the value of MyOutput (the data after analysis)

?> -------------------------------------------
The first line is an include Command to provide the PHPLIB template function. Of course, PHPLIB does more than the template, but if you only want to use the template features, you only need to include tmplate. inc (template. inc is one of the files from PHPLIB ). The PHPLIB template uses object-oriented programming, so the next thing is to create a template object. Code "/Home/mydir/mytemplates/");?> Create a new template object $ t. This $ t object is a handle that will be used to process all template functions for other code in the PHP script. If you want to, you may create other template objects (each with its own template variable namespace), but one is enough. The path ("/home/mydir/mytemplates/") in the template constructor call is used to set the root directory where your template is located, but if you do not set it, by default, it will be the same as the directory where your PHP script is located.

Then, we call set_file () to define a handle named "MyFileHandle" to link it with MyTemplate. ihtml (the template will not actually be loaded before parse () is called ). By the way, the file name suffix of the PHPLIB template is. ihtml. you can use .html,. tpl, or other suffixes. Call set_var () to set the value of the template variable some_color to $ my_color (the value is "blue "), this means that all the places where {some_color} appears in the template will be replaced by the word "blue", once we call parse ().

Next we call parse (), which loads MyFileHandle (MyTemplate. ihtml) for analysis, and replace all template variables ("{a variable}") with the value of the template variable, the analysis results are placed in MyOutput. No results will be output to the web server, unless p ("MyOutput") is called, it will output the last analyzed text.

  

Nested template
One clever feature of the parse () function is that the MyOutput handle it creates is a real template variable, just as some_color is a template variable. So if you have another template, it has a {MyOutput} tag. when you analyze the second template, all the {MyOutput} tags will be replaced with the analyzed text in MyOutput. This feature allows you to embed a template file into another template. Therefore, we may have another template named wholePage. ihtml with the following content:

Sorry, you did not win. But if you win, we will say: {MyOutput}

After wholePage. ihtml is analyzed, the final result will be:

Sorry, you did not win. But if you win, we will say: Congratulations! You win a new blue Honda Prelude!

The following is the PHP code for analyzing the two templates:

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

$ T = new Template ("/home/mydir/mytemplates /");

// These three rows are the same as those in the first example $ t-> set_file ("MyFileHandle", "MyTemplate. ihtml ");
$ T-> set_var ("some_color", $ my_color );
$ T-> parse ("MyOutput", "MyFileHandle ");

// Note that we didn't call p () // here, nothing is output

// Analyze the second template
$ T-> set_file ("WholeHandle", "wholePage. ihtml ");

// WholePage. ihtml has "{MyOutput}" in it $ t-> parse ("MyFinalOutput", "WholeHandle ");

// All {MyOutput} are replaced with $ t-> p ("MyFinalOutput ");
// Output the value of MyFinalOutput

?> ---------------------------------------------------
Finally, the two rows of parse () and p () can be combined into a short function pparse ():

-------------------------------------------------
Pparse ("MyFinalOutput", "SecondHandle ");
?>
-------------------------------------------------
Another PHPLIB template features the set_file () and set_var () functions can also receive multiple sets of values at a time by passing a handle/array pair array. This is an example:


-----------------------------------------
$ T-> set_file (array ("pageOneHandle" => "pageone. ihtml ",
"PageTwoHandle" => "pagetwo. ihtml "));
$ T-> set_var (array ("last_name" => "Gates ",
"First_name" => "Bill ",
"Net_worth" => $ reallybignumber ));
?>
-----------------------------------
Add template text
You can pass the third parameter to parse () and pparse () if you want to append data to the template variable instead of replacing it. You can simply use true as the third parameter to call parse () and pparse (), for example:


--------------------------------------------
$ T-> parse ("MyOutput", "MyFileHandle", true );
?>
-----------------------------------------------------
If MyOutput already contains data, MyFileHandle will be analyzed and appended to the existing data of MyOutput. This technique is very useful. if you already have a template, you want to repeat the same text for multiple times, for example, listing multiple rows in a database query result. You may also display the variables in the array, as shown in the following example:


---------------------------------------------
Set_file (array ("mainpage" => "mainpage. ihtml "," each_element "=>" each_element.ihtml "); reset ($ myArray); while (list ($ elementName, $ elementValue) = each ($ myArray )){
// Set 'value' and 'Name' to the values and names of each element.
$ T-> set_var ("name", $ elementName); $ t-> set_var ("value", $ elementValue );
// Append an each_element copy.
$ T-> parse ("array_elements", "each_element", true);} $ t-> pparse ("output", "mainpage");?> --------------------------------------
In this example, two templates are used: mainpage. ihtml and each_element.ihtml. The mainpage. ihtml template may be like this:


Here is the array:



{Array_elements}


The above {array_elements} tag will be replaced by a copy of each_element.ihtml, which will be repeated according to the array ($ myArray. The each_element.ihtml template may look like:


{Name }:{ value}

The processing result is a well-formatted table containing $ myArray elements. But isn't it better to combine the two templates into one? In fact, they can be combined using template blocks. The template block allows you to extract a piece of text from a template, so you can repeat it multiple times or do anything you want on it. But I will talk about this feature in another article.

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.