この記事で分かること
Twigの亜空間殺法(嘘)
背景
自前でTemplateEngineみたいなことをしようとしたときに、そもそもPHPでTwig使ってるんだからそれ使えば良くない? ってなったので、調べた。結論を言うとやりたいことより複雑性が高かったので今回採用はしなかった。
Twig はこちら
Twig for Developers - Documentation - Twig - The flexible, fast, and secure PHP template engine
コード
なんかPHPのシンタックスハイライト効いてるのか効いてないのかわからん……
use Twig_Loader_Array; use Twig_Environment; $targetTxt = "You are {{ replaceText }} ?"; $loader = new Twig_Loader_Array(['index.html' => $targetText]); $twig = new Twig_Environment($loader); try { $res = $twig->render('index.html', ['replaceText' => 'hogehogewww']); } catch(Exception $e) { var_dump($e); } $res; // "You are hogehogewww ?"
Twig_Loader_Array
でインメモリに index.html
をKeyとしてTemplateを束縛。
束縛したTempleteをRenderするときに連想配列で置換したい内容を挿入。
なるほどなぁ。