Home > Article > PHP Framework > How to use ThinkPHP6’s template engine
ThinkPHP6 is a popular PHP framework currently. It provides many convenient features and tools, one of which is the built-in template engine. This article will introduce how to use the template engine in ThinkPHP6.
1. Create a template file
First, we need to create a template folder in the project, the path is: /application/index/view/
, this folder Store our template files.
Next, create a new index.html file in the template folder. This file will serve as our template file.
2. Template syntax
ThinkPHP6 uses the Twig template engine and adds its own extension functions. Let's learn the basics of using it.
Use {{}}
syntax to output variables. For example: {{title}}
will output the value of the variable $title. Note that variable names do not need to use $
symbols.
The if statement uses {% if condition %} ... {% endif %}
syntax. For example:
{% if isLogin %} <a href="#">退出登录</a> {% else %} <a href="#">登录</a> {% endif %}
foreach statement uses {% for key, value in array %} ... {% endfor %}
grammar. For example:
{% for article in articles %} <div class="article"> <h2>{{article.title}}</h2> <p>{{article.content}}</p> </div> {% endfor %}
include statement can introduce other template files, using {% include "file.html" %}
syntax. For example:
{% include "header.html" %} <div class="content"> ... </div> {% include "footer.html" %}
3. Using templates in controllers
We need to pass data to the template engine in the controller and then render the template.
The code to load the template engine and render the template in the controller is as follows:
<?php namespace appindexcontroller; use thinkController; class Index extends Controller { public function index() { $this->assign('title', 'Welcome to my blog'); $this->assign('isLogin', true); $this->assign('articles', [ ['title' => 'article 1', 'content' => 'something'], ['title' => 'article 2', 'content' => 'something else'] ]); return $this->fetch('index'); } }
In the above code, the assign
method passes data to the template engine. title
, isLogin
and articles
are the variable names we use in the template file. The
fetch
method is used to render the template file, and its parameter is the template file name, which is index.html
.
4. Conclusion
The above is the basic method of using the template engine in ThinkPHP6. The template engine makes it easier for us to display data in the form of pages, and also improves the readability of the code. Come and try it out!
The above is the detailed content of How to use ThinkPHP6’s template engine. For more information, please follow other related articles on the PHP Chinese website!