【PHP日記】

自分の知識不足を悟った末、なるべく1日一回、Webに関する知識を書いていくだけのブログ。

テンプレートエンジン『twig』の使い方 【29日目】

使う機会があったので、今回は『Symfonyフレームワークの標準テンプレートである『twig』の使い方を簡単にまとめていきます。


twigの準備


『twig』のインストール

まずパッケージ管理マネージャの『composer』を使用して、『twig』をインストールをしていきます。

ルートディレクトリに「composer.json」ファイルを作成し、以下の内容で保存します。

{
   "require":{
      "twig/twig":"~1.0"
   }
}

次に、ターミナルで次のコマンドを実行し、twigをインストールしていきます。

composer update

「vendor」フォルダと「conposer.lock」ファイルがインストールされていればOKです。


テンプレートフォルダの指定

次に、PHP側でテンプレートファイル(.html.twig)が置かれているフォルダを指定します。

キャッシュフォルダも同時に指定するとパフォーマンスが上がりますが、不具合が起こる可能性があります。

$loader = new \Twig_Loader_Filesystem(テンプレートフォルダの指定);
$twig = new \Twig_Environment($loader, [
  'cache' => キャッシュフォルダの指定
]);



『twig』の読み込み

最後にPHP側からtwigを読み込むためのコードを書けば完了です。

require_once dirname(__FILE__) . './../vendor/autoload.php';



基本的な文法

for文
{% for key, val in qs %}
<tr>
<th>{{ val }}</th>
<td><input type="radio" name="{{ val }}" value="1" required></td>
<td><input type="radio" name="{{ val }}" value="2" required></td>
<td><input type="radio" name="{{ val }}" value="3" required></td>
<td><input type="radio" name="{{ val }}" value="4" required></td>
</tr>
{% endfor %}


if文
{% if err_msg is not empty %}
    <p>{{ err_msg }}</p>
{% endif %}


定数
<link rel="stylesheet" href="{{constant('exam\\Bootstrap::ENTRY_URL')}}css/style.css" type="text/css">


別ファイルの読み込み
{% include 'category_menu.html.twig' %}



以上です。