CI4 twig 整合
-
首页在ThirdParty目录下面创建一个 Twig 目录,然后,创建一个 composer.json 文件,内容为:
{
“require”: {
“twig/twig”: “^3.0”
}
} -
执行composer update,拉取成功如下图,多出vendor文件夹 和 compsoer.lock
-
在config目录下面创建一个Twig.php,参数说明:https://www.kancloud.cn/yunye/twig-cn/159459
APPPATH ,WRITEPATH 都是CI4 内置的常量
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Twig extends BaseConfig
{
// 默认后缀
public $extension = '.twig';
// 默认模版路径
public $template_dir = APPPATH . 'Views/';
// 缓存目录
public $cache_dir = WRITEPATH . 'cache/twig/';
// 调试模式
public $debug = true;
// 编码
public $charset = "UTF-8";
// 是否使用严格变量模式
public $strict_variables = false;
// 是否全局自动转义
public $autoescape = 'html';
//是否编译优化,-1全部优化(默认值) 0禁用
public $optimizations = -1;
// 缓存
public $cache = false;
// 自动刷新
public $auto_reload = true;
}
- 在Libraries目录下面创建Twig.php
内容为:
<?php
namespace App\Libraries;
require_once APPPATH.'ThirdParty/Twig/vendor/autoload.php';
class Twig
{
private $twig_config;
public $twig;
public $config;
public function __construct()
{
$this -> twig_config = new \Config\Twig();
$options = array(
'debug' => $this->twig_config->debug,
'charset' => $this->twig_config->charset,
'strict_variables' => $this->twig_config->strict_variables,
'autoescape' => $this->twig_config->autoescape,
'auto_reload' => $this->twig_config->auto_reload,
'optimizations' => $this->twig_config->optimizations,
);
if($this->twig_config->cache)
{
$options['cache'] = $this->twig_config->cache_dir;
}
$this->config = array(
'extension' => $this->twig_config->extension,
'template_dir' => $this->twig_config->template_dir,
'cache_dir' => $this->twig_config->cache_dir,
);
$loader = new \Twig\Loader\FilesystemLoader($this->config['template_dir']);
$this->twig = new \Twig\Environment($loader, $options);
}
/**
* Created by PhpStorm.
* 输出 模板到浏览器
*/
public function view($template, $data = array())
{
if($template == "")
{
return;
}
if(substr($template, - strlen($this->twig_config->extension)) != $this->config['extension'])
{
$template .= $this->config['extension'];
}
$template = $this->twig->load($template);
echo htmlspecialchars_decode($template->render($data),ENT_QUOTES | ENT_HTML5);
}
/**
* Created by PhpStorm.
* 返回 渲数据模板
*/
public function load($template, $data = array())
{
if($template == "")
{
return false;
}
if(substr($template, - strlen($this->twig_config->extension)) != $this->config['extension'])
{
$template .= $this->config['extension'];
}
$template = $this->twig->load($template);
return htmlspecialchars_decode($template,ENT_QUOTES | ENT_HTML5);
}
}
-
在 BaseController (任意公共Controller) ,下面引入之前在Libraries目录下面创建的twig文件
-
然后在Config\Services 目录下面创建方法
-
在任意一个Controller文件下面测试,需要继承BaseController
-
在views目录下面创建index.twig 文件
-
ok
-
由于CI 默认视图是.php 后缀的,所以就在渲染模板的时候,给他加上.twig