LoginSignup
14
12

More than 5 years have passed since last update.

PHP: 5行でテンプレートエンジンを作る

Posted at

欲しいもの

$template = '<a href="{url}" class="{class}">{text}</a>';

というテンプレートと

$variables = [
    'url'   => 'http://example.com',
    'class' => 'btn btn-default',
    'text'  => 'テスト',
];

という変数を渡すと

<a href="http://example.com" class="btn btn-default">テスト</a>

という文字列を返してくれる関数が欲しい。RubyやPythonなら、sprintfや%でかけちゃいますが、PHPはそういう関数がないんですよね・・・。Output Buffer Filterと<?=を組み合わせたり、文字列の変数展開とextractを組み合わせたりすればPHPでも近いことはできますが、ハック感があるので今回は文字列操作の関数だけで実装してみました。

関数の実装

function render($template, array $vars) {
    return preg_replace_callback('/{(\w+)}/', function($m) use ($vars) {
        return $vars[$m[1]];
    }, $template);
}

使い方

$result = render('<a href="{url}" class="{class}">{text}</a>', [
    'url'   => 'http://example.com',
    'class' => 'btn btn-default',
    'text'  => 'テスト',
]);
assert($result === '<a href="http://example.com" class="btn btn-default">テスト</a>');
14
12
5

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
12