Home > Article > PHP Framework > thinkphp template execution method
ThinkPHP is a popular PHP framework. It has a powerful template engine that can realize the separation of PHP controller and HTML view, improving development efficiency and maintainability. This article will introduce several commonly used execution methods of template engines in ThinkPHP.
1. Passing variables
Passing variables is the basic operation of the template engine. You can output variables in PHP in the template. For example:
In the PHP controller, we define a variable $name:
$name = 'John Doe'; $this->assign('name', $name);
In the HTML view, we output the variable through the template tag:
<html> <head> <title>Hello <?php echo ($name); ?></title> </head> <body> <h1>Hello <?php echo ($name); ?></h1> </body> </html>
Here The basic syntax of the template engine is used, that is, $name
is the variable name in the template tag, and ($name)
is the syntax for outputting the variable.
2. Loop output
Loop output is one of the commonly used syntaxes in template engines. We can use foreach
to loop through arrays in PHP. For example:
Suppose we define an array in the PHP controller:
$data = array( array('name'=>'John Doe', 'age'=>20), array('name'=>'Jane Doe', 'age'=>18) ); $this->assign('data', $data);
In the HTML view, we use foreach
to loop and output the array in sequence:
<html> <head> <title>Student List</title> </head> <body> <h1>Student List</h1> <ul> <?php foreach($data as $item): ?> <li><?php echo ($item['name']); ?> - <?php echo ($item['age']); ?></li> <?php endforeach; ?> </ul> </body> </html>
Two statements in the template engine are used here, foreach
and endforeach
, and $item
is used in the loop statement to represent each item in the loop array element.
3. Conditional judgment
In addition to loop statements, the template engine also supports conditional judgment statements. Different HTML content can be output based on the value of variables in PHP. For example:
Define a variable $is_valid in the PHP controller:
$is_valid = true; $this->assign('is_valid', $is_valid);
In the HTML view, use if-else
to determine the variable value and output different HTML Content:
<html> <head> <title>Welcome</title> </head> <body> <?php if($is_valid): ?> <h1>Welcome</h1> <?php else: ?> <h1>Access Denied</h1> <?php endif; ?> </body> </html>
The if-else
statement and endif
end statement in the template engine are used here to output different titles according to the value of the variable $is_valid.
The above are several commonly used execution methods in ThinkPHP template engine, which can be selected according to actual needs. The use of template engines can improve development efficiency and code maintainability, and developers are recommended to use it more.
The above is the detailed content of thinkphp template execution method. For more information, please follow other related articles on the PHP Chinese website!