假设你的项目项目使用composer
1. 安装,为了兼容php5.4使用的是1.x版本
composer require twig/twig:~1.0
2. 封装为trait以集成
namespace objects\Traits; trait DoufuTwig { /** * @var \Twig_Environment */ private $twig; protected function renderTwig($path, $data = []) { if (! $this->twig) { $loader = new \Twig_Loader_Filesystem(APPPATH . 'views'); $this->twig = new \Twig_Environment($loader, array( 'cache' => APPPATH . 'cache', 'auto_reload' => true )); } return $this->twig->render($path, $data); } }
3. 使用
集成到控制器父类
namespace Ncontrollers; use objects\Traits\DoufuTwig; abstract class Controller { use DoufuTwig; }
控制器内使用
... echo $this->renderTwig('xxx/login.html'); ...