hysryt / wiki

https://hysryt.github.io/wiki/
0 stars 0 forks source link

Twig #114

Open hysryt opened 5 years ago

hysryt commented 5 years ago

PHPテンプレートエンジン https://github.com/twigphp/Twig

2020年2月12日現在でも更新が続いている。 2020年2月11日にバージョン3がリリースされた。

hysryt commented 5 years ago

インストール

$ composer require twig/twig
Using version ^2.7 for twig/twig
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 3 installs, 0 updates, 0 removals
  - Installing symfony/polyfill-ctype (v1.11.0): Downloading (100%)
  - Installing symfony/polyfill-mbstring (v1.11.0): Downloading (100%)
  - Installing twig/twig (v2.7.4): Downloading (100%)
Writing lock file
Generating autoload files
hysryt commented 5 years ago

Hello, world

helloworld.php

<?php

require_once './vendor/autoload.php';

$loader = new \Twig\Loader\FilesystemLoader('./templates');
$twig = new \Twig\Environment($loader);

echo $twig->render(
  'index.twig',
  [
    'name' => 'Fabien'
  ]
);
echo PHP_EOL;

templates/index.twig

Hello, {{ name }}

$ php ./helloworld.php 
Hello, Fabien

Loader

テンプレートローダー。 Loader にはいくつか種類があるが、基本的に FilesystemLoader を使用することが多いはず。

Environment

Twig 設定を保持する。 Twig に対する操作はこのインスタンスに対して行う。 Environment と Loader は一対一の関係。 レンダリングする際は render メソッドを使用する。