Laravelのyieldで追加するコンテンツがあるかどうかを調べる

Laravelのyieldで追加するコンテンツが無い場合、空の状態になってしまいます。
yieldで追加するコンテンツがあるかどうかを調べて、ある場合とない場合で出力するコードを制御してみます。

サンプルコード

head内が共通で各ページ毎にtitle,keywords,descriptionが設定できるになっているサイトがあるとして、そのサイト内でkeywordsとdescriptionが不要になるページがある想定で試してみます。
まずは普通にhead内を共通にしてみます。

app\Http\routes.php

Route::get('/page', function() {
	return view('page.index');
});

resources\views\layout\common.blade.php

<DOCTYPE HTML>
<html lang="ja">
<head>
@yield('head')
</head>
<body>
<div class="contents">
@yield('content')
</div>
</body>
</html>

resources\views\layout\head.blade.php

@section('head')
<meta charset="UTF-8">
<title>@yield('title') | cly7796.net</title>
<meta name="description" itemprop="description" content="@yield('description')">
<meta name="keywords" itemprop="keywords" content="@yield('keywords')">
@endsection

resources\views\page\index.blade.php

@extends('layout.common')

@section('title', 'ページタイトル')
@section('keywords', 'A,B,C')
@section('description', '説明文')

@include('layout.head')

@section('content')
<p>コンテンツ内容</p>
@endsection

これで/pageでは以下のコードが出力されました。

HTML

<DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ページタイトル | cly7796.net</title>
<meta name="description" itemprop="description" content="説明文">
<meta name="keywords" itemprop="keywords" content="A,B,C">
</head>
<body>
<div class="contents">
<p>コンテンツ内容</p>
</div>
</body>
</html>

ページ毎でtitle,keywords,descriptionが設定できます。

keywordsとdescriptionが不要になるページの想定で、keywordsとdescriptionを削除してみます。

resources\views\page\index.blade.php

@extends('layout.common')

@section('title', 'ページタイトル')

@include('layout.head')

@section('content')
<p>コンテンツ内容</p>
@endsection

以下のようにkeywordsとdescriptionが空の状態でコードが出力されました。

HTML

<DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ページタイトル | cly7796.net</title>
<meta name="description" itemprop="description" content="">
<meta name="keywords" itemprop="keywords" content="">
</head>
<body>
<div class="contents">
<p>コンテンツ内容</p>
</div>
</body>
</html>

これでも一応問題はなさそうですが、タグ自体を出力しないようにしてみます。

resources\views\layout\head.blade.php

@section('head')
<meta charset="UTF-8">
<title>@yield('title') | cly7796.net</title>
@if (View::hasSection('description'))
<meta name="description" itemprop="description" content="@yield('description')">
@endif
@if (View::hasSection('keywords'))
<meta name="keywords" itemprop="keywords" content="@yield('keywords')">
@endif
@endsection

yieldで追加するコンテンツが無い場合、タグ自体を出力しないようにすることができました。

HTML

<DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>ページタイトル | cly7796.net</title>
</head>
<body>
<div class="contents">
<p>コンテンツ内容</p>
</div>
</body>
</html>

 

【参考サイト】

 

このエントリーをはてなブックマークに追加

関連記事

コメントを残す

メールアドレスが公開されることはありません。
* が付いている欄は必須項目です

CAPTCHA


コメントが承認されるまで時間がかかります。

2024年4月
 123456
78910111213
14151617181920
21222324252627
282930