LoginSignup
9
9

More than 5 years have passed since last update.

Laravel Blade拡張

Last updated at Posted at 2016-10-31

はじめに

  • Laravel5.3

Bladeの拡張メソッドの追加方法
デフォルトで用意されている下記のようなメソッドは簡単位追加することが可能。

@if(true)
@elseif
@endif

公式ドキュメントを見るとdirectiveメソッドと呼ばれるもので拡張を行うとある。

公式の拡張例では下記のようなコードとなっておりBladeテンプレート内で@datetime($datetime)のような形で渡すことで'm/d/Y H:i'のようなフォーマットにしてくれるメソッドを追加している。

次の例は@datetime($var)ディレクティブを作成し、渡されるDateTimeインスタンスの$varをフォーマットします。

<?php

namespace App\Providers;

use Illuminate\Support\Facades\Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * サービスの初期起動後に登録する
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function($expression) {
            return "<?php echo $expression->format('m/d/Y H:i'); ?>";
        });
    }

    /**
     * コンテナへ結合を登録する
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

他にも条件式のようなメソッドを追加することも可能で実際に@ifの中身をみてみると

Illuminate\View\Compilers\BladeCompiler
    /**
     * Compile the if statements into valid PHP.
     *
     * @param  string  $expression
     * @return string
     */
    protected function compileIf($expression)
    {
        return "<?php if{$expression}: ?>";
    }

このようになっており、条件式を渡すだけとなっている。

ログイン状況返却の追加

これを自分だけの条件式にすることも可能で例えばログイン状況やログイン名について返却したい場合下記のように追加することが可能となっている。
このメソッド時代はViewが呼ばれる前に追加しておけばBlade内で参照することが可能で、今回のようなAuthを使用する場合は共通コントローラに記載することが可能となっている。

        Blade::directive('ifauth', function() {
            return "<?php if(\Auth::check()): ?>";
        });

        Blade::directive('authname', function() {
            return "<?php echo \Auth::user()->name; ?>";
        });

これをBladeで呼び出す場合

@ifauth
  @authname
@else
  ゲスト
@endif

というように呼び出すことが可能。
ちなみに@else@endifは特に追加する必要はなく共通して使用することが可能。
これは単純にphpのelseとendifを使用しているため。

Illuminate\View\Compilers\BladeCompiler

    protected function compileElse($expression)
    {
        return '<?php else: ?>';
    }

    protected function compileEndif($expression)
    {
        return '<?php endif; ?>';
    }

まとめ

Bladeテンプレートにはできるだけロジックは書かない方が綺麗なソースになりそう。
共通な処理はできるだけメソッド化して呼び出すのが読みやすいソースを作ることになる。

参考

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