Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Custom template engine for front-end learning PHP

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >

Share

Shulou(Shulou.com)06/02 Report--

What is a website template? To be exact, it refers to the website page template, that is, each page is only a board, including structure, style and page layout, is a template for creating web content, and can also be understood as an existing web frame. The original content in the template can be replaced with dynamic content from the server-side database in order to keep the page style consistent.

PHP is a HTML embedded scripting language that executes on the server side, so the initial development template for most Web applications developed by PHP is mixed-layer data programming. Although the application logic can be forcibly separated from the web presentation logic through the MVC design pattern, it only separates the input, processing and output of the application, and the web rendering logic (view) will be strongly coupled with HTML code and PHP programs. The writer of PHP script must be both a web designer and a PHP developer

There are many solutions that can almost completely separate the page design of a website from the PHP application. These solutions, called "template engines", are gradually eliminating the challenges caused by the lack of hierarchical separation. The purpose of the template engine is to achieve the function of logical separation mentioned above. It allows program developers to focus on data control or the achievement of functions. Therefore, the template engine is very suitable for the company's Web development team to use, so that everyone can develop their expertise.

The core of template engine technology is relatively simple. Just specify the front-end page as a template file, and define the dynamic content in the template file, such as database output, user interaction, and so on, to use the "variables" contained in the special "delimiter". Then put it in the appropriate location in the template file. When the user browses, the PHP script opens the template file and replaces the variables defined in the template file. In this way, when the special variables in the template are replaced with different dynamic content, the desired page will be output

At present, there are many mature templates that can be used in PHP, such as Smarty, PHPLIB, IPB and so on. Using these template engines written through PHP can make the code context clearer and the structure more reasonable. It can also make it easier to maintain and update the website, create a better development environment, and make it easier to combine development and design work. However, no PHP template is the most appropriate and perfect. Because PHP templates are popular things, not developed for anyone. If we have a clear understanding of the characteristics and application of the template, and fully realize the advantages and disadvantages of the template, we can know whether to choose to use the template engine or which template engine to use.

Custom template engine class

Custom template engine can better grasp the working mechanism of template engine and prepare for learning Smarty. More importantly, your own PHP template engine is never fixed and can be tailored to the needs of the project.

In the following example, a simple template engine of your own is created through the template engine concept described earlier, which can be used to handle the basic functions of the template. For example: variable substitution, branching structure, array loop traversal, and nesting between templates, as follows:

* /'$this- > stripvtags (\'\',\'${2}\')', / * replace elseif string * /'$this- > stripvtags (\'\', ")', / * replace else string * /' / * the following two entries are used to replace the loop identifiers in the template with foreach format * /'${3}','${4}' / * replace the include string * / 'file_get_contents ($this- > template_dir. "/ ${1}")') / * use regular substitution functions to handle * / $repContent = preg_replace ($pattern, $replacement, $content) / * if there is a logo to be replaced, recursively call itself to replace * / if (preg_match ('/'. $left.' ([^ ('. $right.')] {1,}). $right.'/', $repContent) {$repContent = $this- > tpl_replace ($repContent) } / * returns the replaced string * / return $repContent } / * * Private methods used internally Used to replace the variable used in the conditional statement with the corresponding value @ param string $expr provides the opening tag @ param string $statement of the conditional statement in the template provides the closing tag @ return strin of the conditional statement in the template concatenates the processed conditional statement and returns * / private function stripvtags ($expr $statement='') {/ * regular * / $var_pattern ='/\ s*\ $([AmurzAmurz _\ x7f -\ xff] [a-zA-Z0-9 _\ x7f -\ xff] *). / * replace the variable with the value * / $expr = preg_replace ($var_pattern,'$this- > tpl_vars ["${1}"]', $expr); / * escape the quotation marks in the opening tag * / $expr = str_replace ("\", "\", $expr) / * replace the quotation marks in the body of the statement and the closing tag * / $statement = str_replace ("\\", "\", $statement); / * join the processed conditional statements and return * / return $expr.$statement;}? >

Of the multiple methods declared in the Mytpl class, except for the encapsulated methods, only two public methods, assign () and display (), can be used after the object is created. The assign () method is used to assign the data in the PHP script to the corresponding variables in the template, and the display () method is used to load the template files in a specific templates directory into the PHP script. At the same time, the custom template statements declared with the ">" tag in the template file are matched and replaced with the corresponding PHP syntax format, and then the replaced content is saved in a specific templates_c directory. At run time, it is also compiled into a non-template PHP file and saved with the template file name prefixed with "com_" and the extension ".php". Then the processed template file is included by the include () function, and parsed by PHP and sent to the client.

Use the template engine

It is easy to use a custom template engine, all of which are self-defined syntax formats. Keep in mind, however, that all popular template introduction solutions follow the same set of core implementation principles, that is, like programming languages, learning one language makes it easier to master other languages. The main reason for using the template engine is to separate the work of the front-end engineer from the back-end engineer, so the template engine needs to be used not only by the back-end engineer, but also by the front-end engineer.

1. Back-end engineer's use of template engine

Include the file where the template engine class is located in the PHP script. As follows:

Require ("mytpl.class.php"); / / contains template engine classes, which is equivalent to template engine installation

Create an object of the template engine class and initialize some member properties. As follows:

$tpl=new MyTpl (); / / create an object of the template engine class, or initialize the member based on the parameter

Assign dynamic data (including scalar and array types, such as arrays of data obtained from tables in the database) to the template file using the assign () method in the template engine object, which can be used multiple times to assign any number of variables to the template. As follows:

$tpl- > assign ("var", "this is a value"); / / you can assign scalar type data, and you can use $tpl- > assign ("arr", array (array (1Power2), array ("a", "b")) multiple times; / / you can also allocate arrays including multidimensional arrays

In the PHP script, by calling the display () method in the template object and passing the template file name as a parameter, the corresponding template file in the specified directory is loaded into the PHP script. Then parse the custom syntax in the template through the replacement method in the template engine, and then output the processed template. As follows:

$tpl- > display ("test.tpl"); / / Parameter "test.tpl" is a template file in a specific directory

2. Front-end engineer's use of template engine

The front-end engineer needs to store the written template files in the specified directory, which is specified by using the $template_dir attribute in the template object, and the default setting is the "templates" directory under the current directory. In addition, template files can be named and suffixed at will, such as index.tpl, test.htm, header.tp;, etc.

Template files are written in pure static negative by using Web foreground languages such as HTML, CSS and javascript. However, you can define a variable between the two delimiters in the template file (similar to the variable format in PHP), which can accept and output dynamic data assigned by the PHP script. The two delimiter pairs used in the template can also be modified in the template engine class according to your personal preference. As follows:

Name:, age:, gender: / / placeholders are used in templates

If you assign an array to a template in a PHP script, you can also traverse it in the template, and you can traverse the multidimensional array in a nested manner. The "" tag pair defined in the template engine is used in a manner similar to the syntax format of the foreach structure in PHP. As follows:

/ / traversing the element value in the element value array in the array $arr / / traversing the value in the output element every time / / traversing the closing tag of the array in the template $value} > / / traversing the element subscript in the array $arr and the element key in the element value array / / traversing the element in the output element every time The element value in the subscript array of / / traverses the value in the output element every time / / traverses the closing tag of the array in the template / / traverses the element value in the array $arr / / traverses the element value in the two-dimensional array using nested tags / / Each traversal of the value in the output element / / traverses the inner closing tag of the array in the template / / traverses the outer closing tag of the array in the template

The template engine can also parse branch structures written with special tags in template files, and the syntax style is similar to the branch structure of PHP. The selection structure is realized by using the "" tag pair in the template file, as well as the selection structure of multi-branch and nested branches. As follows:

This is the word "red".

This is the word "green".

This is a word the size of "20px"

In the custom template engine, the ability to include other template files in the template file has also been added. You can use the "" tag to include a subtemplate in the current template, and you can also include additional subtemplates in the subtemplate again. As follows:

Use examples to analyze

The code of the front-end language can be separated from the back-end language by loading the template engine in the program. First, the data stored in the database is obtained in the PHP program, and then the data is allocated by loading the template engine, and then the template file is loaded and processed by the template engine and output. So the PHP program just creates the dynamic data, loads the template engine and assigns the dynamic data to the template, and completes the work of the PHP program. The design of the template only needs to be completed independently by the front-end engineer, using foreground page design languages such as HTML, CSS and javascript. In addition, in the template file, you need to use tags that can be parsed by the template engine to reference the dynamic data allocated in the PHP in the template.

1. The design of database

Suppose the database server is on the "localhost" host with the user name and password of "admin" and "123456", respectively. Create a database named "mydb" on the server, and create a user table named "User" in the database. The SQL query statement to create the table is as follows:

CREATE TABLE User (id SMALLINT (3) NOT NULL AUTO_INCREMENT, name VARCHAR (10) NOT NULL DEFAULT'', sex VARCHAR (4) NOT NULL DEFAULT'', age SMALLINT (2) NOT NULL DEFAULT'0, email VARCHAR (20) NOT NULL DEFAULT'', PRIMARY KEY (id))

After the user table user has been created, you can then insert some data into the table as an example to demonstrate, as shown in the SQL query statement:

INSERT INTO User (name,sex,age,email) VALUES ("a", "male", 27, "a@a.com"), ("b", "female", 22, "b@b.com"), ("c", "female", 30, "c@c.com"), ("d", "female", 24, "d@d.com")

2. The design of template

The design of the template does not have any PHP code, it can be done by the front-end staff. In the custom template engine, it is stipulated to look for template files in the specified directory, which can be specified when creating template engine objects, or you can use the default directory settings. By default, template files can be stored in the "templates" directory in the current directory. This example requires a total of three template files main.tpl, header.tpl, and footer.tpl, all of which are stored in this default directory setting. The code for the three template files is as follows:

The header file header.tpl of the template

The tail file footer.tpl of the template

# #

Master template file main.tpl

The file main.tpl is the main template file, in which separate header and tail template files are included with two tags at the top and bottom of the file, respectively. And in this file, we use tags to obtain the table names dynamically assigned from PHP, and use double-layer tag nesting to traverse the two-dimensional array $Users dynamically allocated from PHP in the database. We also use a combination of conditional selection markers in the tags to set the background of the table whose gender is "male" in the data to red and some other judgments. The included header template file header.tpl and tail template file footer.tpl can also obtain the data dynamically assigned to the template from PHP.

3. PHP programming

Through the use of template engine, PHP programmers only need PHP when writing code, instead of using page design languages such as HTML, CSS and javascript to complete the front-end work. Here is a PHP script file named index.php, in the same directory as the mytpl_class.php file where the template engine class is located. The code is as follows:

In the above PHP script file, connect to the MySQL server through the PDO object, get all the records in the user table User, and save them in the variable data as a two-dimensional array variable of PHP. Then use the included "mytplclss.php" file in the current directory to create and initialize the object data of the template engine class. Then use the included "mytplclss.php" file in the current directory to create and initialize the object tpl of the template engine class. Then assign some data to the template through the assign () method in the object, and then use the display () method in the object to load the template file main.tpl. And replace the special variables marked in the template with the dynamic data assigned from PHP, and output the template page after processing. The output of the page is as follows

Limited to a variety of different conditions, such as time and experience, it is very difficult to make a custom PHP template engine. In fact, what is needed is not to reconstruct a PHP template, but to choose a PHP template that is closest to you and modify it.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Servers

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report