[CodeIgniter3]Twig連携

ひと昔前はテンプレートエンジンといえばSmarty択一だったけど最近はTwig、Bladeとかいろいろ。EC-Cube3がTwig使っていたのでCodeIgniterでも使っていこうと・・・まとめ。

C:\htdocs\sample\composer.json

{
    "description" : "The CodeIgniter Application with Composer",
    "require": {
        "php": ">=5.3.2",
        "codeigniter/framework": "3.1.*",
        "twig/twig": "1.*"					//追記
    },
}
C:\htdocs\sample> composer update

CI_Controller.phpを継承してMY_Controller.php作成。
※デフォルトでは「MY_」を接頭辞しないと認識しない。

application/core/MY_Controller.php

<?php
	class MY_Controller extends CI_Controller {
		protected $twig;
		public function __construct()
		{
		parent::__construct();
		// Twig
		$loader = new Twig_Loader_Filesystem('../application/views');
		$this->twig = new Twig_Environment($loader, array('cache' => APPPATH.'/cache/twig', 'debug' => true));
		// Twigからアクセスできる変数を設定
		$this->twig->addGlobal("xxxxx", $xxxxx);
	}
}

コントローラーの記述

class Sample extends MY_Controller {
	public function test() {
	$data = [];
	// テンプレートを指定して変数を渡す
	$this->twig->display('sample/test.twig', $data);
	}
}