thinkphp6是目前比較流行的一個php框架,它提供了很多方便的特性以及工具,其中之一就是內置的模板引擎。本文將介紹如何在thinkphp6中使用模板引擎。
一、創建模板文件
首先,我們需要在項目中創建一個模板文件夾,路徑為:/application/index/view/,這個文件夾存放我們的模板文件。
接下來在模板文件夾中新建index.html文件,這個文件將作為我們的模板文件。
二、模板語法
立即學習“PHP免費學習筆記(深入)”;
ThinkPHP6使用了Twig模板引擎,并添加了自己的擴展功能。我們來學習它的基本使用方法。
- 輸出變量
使用{{}}語法來輸出變量。例如:{{title}}將輸出變量$title的值。注意,變量名不需要使用$符號。
- if語句
if語句使用{% if condition %} … {% endif %}語法。例如:
{% if isLogin %} <a href="#">退出登錄</a> {% else %} <a href="#">登錄</a> {% endif %}
- foreach語句
foreach語句使用{% for key, value in array %} … {% endfor %}語法。例如:
{% for article in articles %} <div class="article"> <h2>{{article.title}}</h2> <p>{{article.content}}</p> </div> {% endfor %}
- include語句
include語句可以引入其他模板文件,使用{% include “file.html” %}語法。例如:
{% include "header.html" %} <div class="content"> ... </div> {% include "footer.html" %}
三、在控制器中使用模板
我們需要在控制器中將數據傳遞給模板引擎,然后再渲染模板。
在控制器中加載模板引擎并渲染模板的代碼如下:
<?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'); } }
上面的代碼中,assign方法將數據傳遞給模板引擎。title、isLogin和articles是我們在模板文件中使用的變量名。
fetch方法用于渲染模板文件,它的參數是模板文件名,即index.html。
四、結語
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END