Template, Phplib processing mode

Source: Internet
Author: User
Template

If you're wondering what a template is, first take a look at the previous paragraphs of Sascha Schumann's wonderful article "templates-why and how they are used in PHP3" (templates-why and how to use them in PHP3).

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

It's not fasttemplates so, do we really need another article on the Phpbuilder on the template? Well, yes, because there are more than one way to implement a template using PHP. Sascha's article describes how to use fasttemplates, but the PHP base Class library ("Phplib") has its own template implementation.

What's different about them? Fasttemplates was originally transformed from a Perl library. Fasttemplates works well for Perl programs, but it's not ideal for PHP. Kristian Koehntopp the Phplib template from scratch, and as a pure PHP library, it provides a better PHP advantage. One advantage is that Kristian's design uses preg_replace () to analyze the template, which is said to be faster than the ereg_replace () used in fasttemplate. Another benefit of the phplib template is that it allows the dynamic block implementations to be nested, unlike fasttemplates.

Two libraries have very similar features and capabilities, but if you've already used fasttemplates and you want to learn to use phplib templates, you should forget everything you know about fasttemplates. Their features may be similar, but everything the phplib template does is a little bit different than fasttemplates.

Using the Phplib template
Let's start with a simple example. We assume that under/home/mydir/mytemplates/there is a template named MyTemplate, which has some text that may be:

Congratulate! You won a {Some_color}honda prelude!.

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

Congratulate! You won a new blue Honda prelude!.

Here is the result of the PHP script:

---------------------------------------
<?php

Include "Template.inc";

$my_color = "Blue";
will be used in the following

$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 template Variable Some_color = $my_color value

$t->parse ("Myoutput", "Myfilehandle");
Set the template variable myoutput = parsed file

$t->p ("Myoutput");
Output Myoutput value (after our analysis of the data)

?>-------------------------------------------
The first line is an include directive, which is used to provide phplib template functionality. Of course phplib do more than templates, but if you only want to use 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.? $t = new Template (
"/home/mydir/mytemplates/");?> create a new template object $t. This $t object is a handle that will be used to process all of the template functions for other code in the PHP script. If you want, you may create other template objects (each with its own template variable namespace), but one will suffice. The path ("/home/mydir/mytemplates/") in the template's constructor call is used to set the root of your template's location, but if you do not set it, it defaults to the same directory as your PHP script.

Then we call Set_file () to define a handle named "Myfilehandle" to be linked to the mytemplate.ihtml (the template is not actually loaded until parse () is invoked). By the way, the phplib template filename has a suffix of. Ihtml is a habit that you can use. Html,.tpl, or other suffixes. Then call Set_var () to set the value of the template variable Some_color to $my_color (the value is "blue"), meaning that all occurrences of {some_color} in the template will be replaced by the word "blue" once we call Parse ().

Then we call Parse (), which loads the Myfilehandle (mytemplate.ihtml) for analysis and replaces all template variables ("{A variable}") as the value of the template variable, and the result of the analysis is placed in the myoutput. No results are output to the Web server unless P ("Myoutput") is invoked, it outputs the last parsed text.

  

Nested templates
A neat 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, and when you parse the second template, all the {myoutput} tags will be replaced with the parsed text in Myoutput. This feature allows you to embed a template file into another template. So, we might have another template named Wholepage.ihtml, which reads:

Sorry, you didn't win. But if you win, we'll say to you: {myoutput}

And after the wholepage.ihtml is analyzed, the final result will be:

Sorry, you didn't win. But if you win, we will say to you: Congratulations! You won a new blue Honda prelude!.

The following is a PHP code that analyzes two templates:

-------------------------------------------------------
<?php

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

These three lines are as $t->set_file as the first example ("Myfilehandle", "mytemplate.ihtml");
$t->set_var ("Some_color", $my_color);
$t->parse ("Myoutput", "Myfilehandle");

Notice we didn't call P ()//here, still no output anything

Now analyze the second template
$t->set_file ("Wholehandle", "wholepage.ihtml");

Wholepage.ihtml has "{myoutput}" inside $t->parse ("Myfinaloutput", "Wholehandle");

All {myoutput} were replaced with $t->p ("Myfinaloutput");
Value of Output Myfinaloutput

?>---------------------------------------------------
The last two lines that call Parse () and P () can be merged into a shorthand function pparse ():

-------------------------------------------------
<?php
Pparse ("Myfinaloutput", "Secondhandle");
?>
-------------------------------------------------
Another feature of the Phplib template is that the Set_file () and Set_var () functions can also receive multiple sets of values at a time by passing a handle/array of arrays. This is an example:


-----------------------------------------
<?php
$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 a third argument 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 invoke parse () and Pparse (), such as:


--------------------------------------------
<?php
$t->parse ("Myoutput", "Myfilehandle", true);
?>
-----------------------------------------------------
If the myoutput already contains the data, Myfilehandle will be parsed and appended to the myoutput already existing data. This technique is very useful, if you already have a template, you want the same piece of text to be repeated multiple times, such as listing multiple rows in a database query result. You may also be displaying variables in the array, as in the following example:


---------------------------------------------
<?php$t = new Template ("/home/mydir/mytemplates/"); $t->set_file (Array ("MainPage" => "mainpage.ihtml", "Each_element" => "each_element.ihtml")); Reset ($myarray ); while (List ($elementname, $elementvalue) = each ($myarray)) {
Set ' value ' and ' name ' for the values and names of each element
$t->set_var ("name", $elementname); $t->set_var ("value", $elementvalue);
Append copy of Each_element
$t->parse ("Array_elements", "Each_element", True);} $t->pparse ("Output", "mainpage");? >--------------------------------------
This example uses two templates, mainpage.ihtml and each_element.ihtml. The mainpage.ihtml template might be this:

<HTML>
This is the array:
<TABLE>
{array_elements}
</TABLE>
</HTML>
The {array_elements} label above will be replaced by a copy of the each_element.ihtml, which will be duplicated according to the array ($myarray). The each_element.ihtml template may look like this:

<TR>
<td>{name}: {value}</td>
</TR>

The processing result is a well-formed table that contains $myarray elements. But wouldn't it be better if you merged two templates into one template? In fact, they can be combined using template blocks. A template block allows you to remove a piece of text from a template, so you can repeat it many times, or do whatever you want on it. But I will cover 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.