LoginSignup
2
2

More than 5 years have passed since last update.

Phalcon の volt に number_format を追加

Posted at

はじめまして、ゆめみ城田です。
Qiita 初投稿になります。

今日は Phalconフレームワーク の標準テンプレート、
volt を採用した際、number_format関数 が無くて驚いた時の対処を書きます。

PHPの代表的なテンプレートエンジン Smarty や twig には
number_format関数 が標準で用意されています。

Smarty

# $money = 1000; であるとき

{$money|number_format} 円

# 出力結果
1,000 円

twig

{{ money|number_format }} 円

# 出力
1,000 円

しかし、
volt には number_format がありません。。

volt でもこのようなことができないか、
twig のように書いてみたのですがやはり動きませんでした。

しかし、
下記のようにDIコンテナに volt を入れる部分で
number_format関数 を指定すれば使えることがわかりました。

  • bootstrap スクリプトなどで
$di = new \Phalcon\DI\FactoryDefault();

$di->set('view', function() {
    $view = new \Phalcon\Mvc\View();
    $view->setViewsDir($templatesPath);
    $view->registerEngines([
        ".volt" => function($view) {
            $volt = new \Phalcon\Mvc\View\Engine\Volt($view);
            $volt->setOptions([
                'compileAlways' => TEMPLATE_COMPILE_ALWAYS,
            ]);

            // 下記のようにPHP関数を追加します
            $volt->getCompiler()->addFunction('number_format','number_format');

            return $volt;
        }
    ]);

    return $view;
});
  • volt 側
{{ number_format(money) }} 円

今回の number_format関数 に限らず、
柔軟に追加していけそうです。

2
2
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
2
2