LoginSignup
13
10

More than 5 years have passed since last update.

Laravel5.1 blade yieldの中身で条件分岐したい

Last updated at Posted at 2017-01-30

blade、皆さん使ってますか?

特に、WEBサイトでよくあるレイアウトとコンテンツ領域を分離できたりと、
便利ですよね。

ですが、サイト構築をしていくと、@section の中身によって分岐したい
ケースが出てきました。
この分岐がきれいなbladeの書き方では見つけられず、
ちょっと無理やり感はありますが、やりたかった事は出来たので、
共有とメモです。

結論

$__env->yieldContent('name') にて@sectionにて定義した内容を取得できる

index.blade.php
<title>
@if ($__env->yieldContent('title') === '')
    未定義の場合はサイト名だけを表示
@else
  @yield('title') | サイト名
@endif
</title>

この$__env->yieldContent('title')から取得できることが分かったことにより、
以下のような処理も可能となってきます

index.blade.php
<title>{{ $helper->titleGeneration($__env->yieldContent('title')) }}

//
class helper{
    function titleGeneration($title)
    {
        return $title . ' | サイト名';
    }

$__envとは何か

index.blade.php
echo get_class($__env); //Illuminate\View\Factory

Illuminate\View\Factory @yieldContent

/vendor/laravel/framework/src/Illuminate/View/Factory.php
class Factory implements FactoryContract{
    /**
     * Get the string contents of a section.
     *
     * @param  string  $section
     * @param  string  $default
     * @return string
     */
    public function yieldContent($section, $default = '')
    {
        $sectionContent = $default;

        if (isset($this->sections[$section])) {
            $sectionContent = $this->sections[$section];
        }

        $sectionContent = str_replace('@@parent', '--parent--holder--', $sectionContent);

        return str_replace(
            '--parent--holder--', '@parent', str_replace('@parent', '', $sectionContent)
        );
    }


}
13
10
1

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
13
10