CodeIgniter3でTwigを利用する
CodeIgniter3でテンプレートエンジンにTwigを使用する場合の覚え書き。
Twigとは
Twig は、 PHP で実装されたオープンソースのテンプレートエンジン である。ライセンスはBSDライセンスである。 その構文はPython で実装された Jinja や、Django に近いものになっている。[3] Symfony2 フレームワークでは デフォルトのテンプレートエンジンとして利用されている。 Twig - Wikipedia
Twigのインストール
Composerを使用してインストールします。
composer.jsonにtwigを追加する
"require": {
"php": ">=5.2.4",
"twig/twig": "1.*"
},
applicationディレクトに移動して、以下のコマンドを実行する
$ composer install
applicationディレクトリ内にvendor/twigが作成されます。
application/config/config.phpファイルを変更する
composer_autoloadをtrueに変更します。
$config['composer_autoload'] = TRUE;
Twig用のライブラリを作成
使いやすいようにライブラリを作成します。
application/librariesディレクトリ内にTwig.phpというファイルを作成し、以下の内容を入力します。
画面に表示するためにdisplayメソッド、文字列として取得するためにrenderメソッドを実装しています。
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Twig { const TWIG_CONFIG_FILE = 'twig'; protected $template_dir; protected $cache_dir; private $_ci; private $_twig_env; public function __construct() { $this->_ci =& get_instance(); $this->_ci->config->load(self::TWIG_CONFIG_FILE); $this->template_dir = $this->_ci->config->item('template_dir'); $this->cache_dir = $this->_ci->config->item('cache_dir'); $loader = new Twig_Loader_Filesystem($this->template_dir, $this->cache_dir); $this->_twig_env = new Twig_Environment($loader, array( 'cache' => $this->cache_dir, 'auto_reload' => TRUE )); } public function render($template, $data = array(), $render = TRUE) { $template = $this->_twig_env->loadTemplate($template); return ($render) ? $template->render($data) : $template; } public function display($template, $data = array()) { $template = $this->_twig_env->loadTemplate($template); $this->_ci->output->set_output($template->render($data)); } } ### 設定ファイルの作成
application/configディレクトリ内にtwig.phpというファイルを作成し、以下の内容を入力します。
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); $config['template_dir'] = VIEWPATH; $config['cache_dir'] = APPPATH.'cache';
テンプレートを作成する
application/viewsディレクトリ内にindex.twigファイルを作成し、以下の内容を記入します。
<html> <head> <title>test</title> </head> <body> <p>{{ name }}</p> </body> </html>
コントローラーでライブラリを読み込み実行する
public function index() { $this->load->library('twig'); $data = [ 'name' => 'yamada' ]; $this->twig->display('index.twig', $data); }
ブラウザに"yamada"と表示されればOKです。
まとめ
これでCodeIgniterでもTwigを利用することができるようになります。