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)
);
}
}