LoginSignup
8

More than 5 years have passed since last update.

Laravel 4で日本語表記の月リスト生成ヘルパーを自作する

Posted at

日本語表記の月のリストを生成するヘルパーがほしかったので、カスタムマクロを使って自作してみた。

まず、マクロ定義ファイル(app/macros.phpなど)に下記のマクロを定義する。

app/macros.php
Form::macro('selectJaMonth', function ($name, $selected = null, $options = array())
{
    $jaMonths = array(
        '1'  => '1月',
        '2'  => '2月',
        '3'  => '3月',
        '4'  => '4月',
        '5'  => '5月',
        '6'  => '6月',
        '7'  => '7月',
        '8'  => '8月',
        '9'  => '9月',
        '10' => '10月',
        '11' => '11月',
        '12' => '12月',
    );

    return Form::select($name, $jaMonths, $selected, $options);
});

中身はForm::select()をラップして月の配列を渡しているだけ。

次に、app/start/global.phpなどでマクロ定義ファイルを読み込む。

app/start/global.php
require app_path().'/macros.php';

最後に、定義したマクロをビューで呼び出せば、日本語表記の月のリストを生成できる。

Form::selectJaMonth('month')

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
8