ThinkPHP is one of the most popular PHP open-source frameworks in China, based on the MVC design pattern. The template execution method in ThinkPHP allows developers to directly invoke PHP code in the template, enabling flexible page rendering and data presentation. The template engine helps developers quickly build applications, separating logic from presentation and reducing code coupling.
First, create a template file called `test.html` and place it in the `application/view` directory of the project. In this file, we will use the template execution method to display data.
In the controller, we call the template engine to render the template. Here is an example:
// Define controller method public function test() { // Pass parameters $this->assign('title', 'ThinkPHP Template Execution Method'); $this->assign('num', 3); // Render the template return $this->fetch('test'); }
We use the `$this->assign()` method to pass data to the template file for rendering.
In the template file, we use the template execution method to display the data and query results passed from the controller. Here is an example:
<meta charset="UTF-8"> <title>{$title}</title> <p>The number is: {$num}</p> <h3>Data Query and Display:</h3> <p>{<!--?php // Perform a data query $result = Db::name('user')->where('status',1)->select(); // Display data foreach($result as $vo) {?> {$vo['id']}.{$vo['name']}, Age: {$vo['age']}, Gender: {$vo['sex']} <?php } ?-->}</p>
In the template file, you can directly use PHP code (via the `` tags) to perform queries and display results.
By using ThinkPHP's template execution method, developers can conveniently write PHP code in the template, perform data queries, and render page content. This method not only improves development efficiency but also makes the code more modular and easier to maintain. In real-world development, using the template engine speeds up page development and is a powerful tool for enhancing work efficiency.