LoginSignup
6
5

More than 5 years have passed since last update.

Mustache.php でレンダリング時に nl2br を使う

Last updated at Posted at 2014-05-21

Mustache.php で nl2br を使う

概要

値に改行が入ってるときに出力側で br に変更したい場合がある.
リポジトリ の README にも書いてあるけどオブジェクトや連想配列で指定した関数は実行できる.
実行される関数の中で nl2br() を呼び出してレンダリングさせるとうまくいく模様.
似たような感じで php にある関数を用いたい場合も似たような手法がとれそう.

動作確認

とりあえず composer で mustache を入れる.

$ cat composer.json 
{
     "require": {
         "mustache/mustache": "v2.6.0"
     }
}
$ composer install

php ファイルで下記のように書いてみる.( autoload.php の位置とかは環境に合わせて)

<?php

require_once '../vendor/autoload.php';

$mustache = new Mustache_Engine();
$param = array(
  'nl2br' => function($text, $render) {
    return nl2br($render->render($text));
  }
);
$param['body'] = <<<EOF
改行
改行
EOF;

echo $mustache->render(<<<EOF
<!DOCTYPE html>
<html>
<head><title>改行テスト</title></head>
<body>
{{#nl2br}}{{ body }}{{/nl2br}}
</body>
</html>
EOF
, $param);

例えば自分の環境だと下記のような構成になってる.

$ tree -L 2
.
├── composer.json
├── composer.lock
├── vendor
│   ├── autoload.php
│   ├── composer
│   └── mustache
└── web
    └── index.php

ここで web 以下の index.php にアクセスすると下記のような html が出力される

<!DOCTYPE html>
<html>
<head><title>改行テスト</title></head>
<body>
改行<br />
改行
</body>
</html>
6
5
0

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
6
5