Readouble

Laravel 7.x Bladeテンプレート

イントロダクションIntroduction

BladeはシンプルながらパワフルなLaravelのテンプレートエンジンです。他の人気のあるPHPテンプレートエンジンとは異なり、ビューの中にPHPを直接記述することを許しています。全BladeビューはPHPへコンパイルされ、変更があるまでキャッシュされます。つまりアプリケーションのオーバーヘッドは基本的に0です。Bladeビューには.blade.phpファイル拡張子を付け、通常はresources/viewsディレクトリの中に設置します。Blade is the simple, yet powerful templating engine provided with Laravel. Unlike other popular PHP templating engines, Blade does not restrict you from using plain PHP code in your views. In fact, all Blade views are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application. Blade view files use the .blade.php file extension and are typically stored in the resources/views directory.

テンプレートの継承Template Inheritance

レイアウト定義Defining A Layout

Bladeを使用する主な利点は、テンプレートの継承セクションです。初めに簡単な例を見てください。通常ほとんどのアプリケーションでは、数多くのページを同じ全体的なレイアウトの中に表示するので、最初は"master"ページレイアウトを確認しましょう。レイアウトは一つのBladeビューとして、簡単に定義できます。Two of the primary benefits of using Blade are template inheritance and sections. To get started, let's take a look at a simple example. First, we will examine a "master" page layout. Since most web applications maintain the same general layout across various pages, it's convenient to define this layout as a single Blade view:

<!-- resources/views/layouts/app.blade.phpとして保存 -->

<html>
    <head>
        <title>アプリ名 - @yield('title')</title>
    </head>
    <body>
        @section('sidebar')
            ここがメインのサイドバー
        @show

        <div class="container">
            @yield('content')
        </div>
    </body>
</html>

ご覧の通り、典型的なHTMLマークアップで構成されたファイルです。しかし、@section@yieldディレクティブに注目です。@sectionディレクティブは名前が示す通りにコンテンツのセクションを定義し、一方の@yieldディレクティブは指定したセクションの内容を表示するために使用します。As you can see, this file contains typical HTML mark-up. However, take note of the @section and @yield directives. The @section directive, as the name implies, defines a section of content, while the @yield directive is used to display the contents of a given section.

これでアプリケーションのレイアウトが定義できました。このレイアウトを継承する子のページを定義しましょう。Now that we have defined a layout for our application, let's define a child page that inherits the layout.

レイアウト拡張Extending A Layout

子のビューを定義するには、「継承」するレイアウトを指定する、Blade @extendsディレクティブを使用します。Bladeレイアウトを拡張するビューは、@sectionディレクティブを使用し、レイアウトのセクションに内容を挿入します。前例にあるようにレイアウトでセクションを表示するには@yieldを使用します。When defining a child view, use the Blade @extends directive to specify which layout the child view should "inherit". Views which extend a Blade layout may inject content into the layout's sections using @section directives. Remember, as seen in the example above, the contents of these sections will be displayed in the layout using @yield:

<!-- resources/views/child.blade.phpとして保存 -->

@extends('layouts.app')

@section('title', 'Page Title')

@section('sidebar')
    @@parent

    <p>ここはメインのサイドバーに追加される</p>
@endsection

@section('content')
    <p>ここが本文のコンテンツ</p>
@endsection

この例のsidebarセクションでは、レイアウトのサイドバーの内容をコンテンツに上書きするのではなく追加するために@@parentディレクティブを使用しています。@@parentディレクティブはビューをレンダーするときに、レイアウトの内容に置き換わります。In this example, the sidebar section is utilizing the @@parent directive to append (rather than overwriting) content to the layout's sidebar. The @@parent directive will be replaced by the content of the layout when the view is rendered.

lightbulb">Tip!! 直前の例とは異なり、このsidebarセクションは@showの代わりに@endsectionで終わっています。@endsectionディレクティブはセクションを定義するだけに対し、@showは定義しつつ、そのセクションを即時にその場所に取り込みます{tip} Contrary to the previous example, this sidebar section ends with @endsection instead of @show. The @endsection directive will only define a section while @show will define and immediately yield the section.

@yieldディレクティブは、デフォルト値を第2引数に受け取ります。この値は埋め込み対象のセクションが未定義の場合にレンダーされます。The @yield directive also accepts a default value as its second parameter. This value will be rendered if the section being yielded is undefined:

@yield('content', View::make('view.name'))

Bladeビューはグローバルなviewヘルパを使用し、ルートから返すことができます。Blade views may be returned from routes using the global view helper:

Route::get('blade', function () {
    return view('child');
});

データ表示Displaying Data

Bladeビューに渡されたデータは、波括弧で変数を囲うことで表示できます。たとえば、次のルートがあるとしましょう。You may display data passed to your Blade views by wrapping the variable in curly braces. For example, given the following route:

Route::get('greeting', function () {
    return view('welcome', ['name' => 'Samantha']);
});

name変数の内容を表示しましょう。You may display the contents of the name variable like so:

Hello, {{ $name }}.

lightbulb">Tip!! Bladeの{{ }}記法はXSS攻撃を防ぐため、自動的にPHPのhtmlspecialchars関数を通されます。{tip} Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks.

ビューに渡された変数の内容を表示するだけに限られません。PHP関数の結果をechoすることもできます。実際、どんなPHPコードもBladeのecho文の中に書けます。You are not limited to displaying the contents of the variables passed to the view. You may also echo the results of any PHP function. In fact, you can put any PHP code you wish inside of a Blade echo statement:

The current UNIX timestamp is {{ time() }}.

エスケープしないデータの表示Displaying Unescaped Data

デフォルトでブレードの{{ }}文はXSS攻撃を防ぐために、PHPのhtmlspecialchars関数を自動的に通されます。しかしデータをエスケープしたくない場合は、以下の構文を使ってください。By default, Blade {{ }} statements are automatically sent through PHP's htmlspecialchars function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

Hello, {!! $name !!}.

Note: note アプリケーションでユーザーの入力内容をechoする場合は注意が必要です。ユーザーの入力を表示するときは、常に二重の波括弧の記法でHTMLエンティティにエスケープすべきです。{note} Be very careful when echoing content that is supplied by users of your application. Always use the escaped, double curly brace syntax to prevent XSS attacks when displaying user supplied data.

JSONのレンダーRendering JSON

JavaScriptの変数を初期化するために、配列をビューに渡してJSONとして描画できます。Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:

<script>
    var app = <?php echo json_encode($array); ?>;
</script>

その際、json_encodeを使う代わりに、@jsonディレクティブを使うことができます。@jsonディレクティブは、PHPのjson_encode関数と同じ引数を受けます。However, instead of manually calling json_encode, you may use the @json Blade directive. The @json directive accepts the same arguments as PHP's json_encode function:

<script>
    var app = @json($array);

    var app = @json($array, JSON_PRETTY_PRINT);
</script>

Note: note @jsonディレクティブは既存の変数をJSONとしてレンダするためだけに使用してください。Bladeテンプレートは正規表現ベースのため、複雑な式をディレクティブに渡すと予期しない不良動作の原因になります。{note} You should only use the @json directive to render existing variables as JSON. The Blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures.

HTMLエンティティエンコーディングHTML Entity Encoding

Blade(およびLaravelのeヘルパ)はデフォルトで、HTMLエンティティをdouble encodeします。double encodeを無効にするには、AppServiceProviderbootメソッドで、Blade::withoutDoubleEncodingメソッドを呼び出してください。By default, Blade (and the Laravel e helper) will double encode HTML entities. If you would like to disable double encoding, call the Blade::withoutDoubleEncoding method from the boot method of your AppServiceProvider:

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * アプリケーションの全サービスの初期処理
     *
     * @return void
     */
    public function boot()
    {
        Blade::withoutDoubleEncoding();
    }
}

BladeとJavaScriptフレームワークBlade & JavaScript Frameworks

与えられた式をブラウザに表示するため、多くのJavaScriptフレームワークでも波括弧を使っているので、@シンボルでBladeレンダリングエンジンに波括弧の展開をしないように指示することが可能です。Since many JavaScript frameworks also use "curly" braces to indicate a given expression should be displayed in the browser, you may use the @ symbol to inform the Blade rendering engine an expression should remain untouched. For example:

<h1>Laravel</h1>

Hello, @{{ name }}.

この例で、@記号はBladeにより削除されます。しかし、{{ name }}式はBladeエンジンにより変更されずにそのまま残り、JavaScriptフレームワークによりレンダリングできるようになります。In this example, the @ symbol will be removed by Blade; however, {{ name }} expression will remain untouched by the Blade engine, allowing it to instead be rendered by your JavaScript framework.

@記号は、Bladeディレクティブをエスケープするためにも使用します。The @ symbol may also be used to escape Blade directives:

{{-- Blade --}}
@@json()

<!-- HTML出力 -->
@json()

@verbatimディレクティブThe @verbatim Directive

テンプレートの広い箇所でJavaScript変数を表示する場合は、HTMLを@verbatimディレクティブで囲めば、各Blade echo文の先頭に@記号を付ける必要はなくなります。If you are displaying JavaScript variables in a large portion of your template, you may wrap the HTML in the @verbatim directive so that you do not have to prefix each Blade echo statement with an @ symbol:

@verbatim
    <div class="container">
        Hello, {{ name }}.
    </div>
@endverbatim

制御構文Control Structures

テンプレートの継承とデータ表示に付け加え、Bladeは条件文やループなどの一般的なPHPの制御構文の便利な短縮記述方法を提供しています。こうした短縮形は、PHP制御構文の美しく簡潔な記述を提供しつつも、対応するPHPの構文と似せています。In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts.

If文If Statements

if文の構文には、@if@elseif@else@endifディレクティブを使用します。これらの使い方はPHPの構文と同じです。You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts:

@if (count($records) === 1)
    1レコードある!
@elseif (count($records) > 1)
    複数レコードある!
@else
    レコードがない!
@endif

便利な@unlessディレクティブも提供しています。For convenience, Blade also provides an @unless directive:

@unless (Auth::check())
    あなたはログインしていません。
@endunless

さらに、すでに説明したように@isset@emptyディレクティブも、同名のPHP関数の便利なショートカットとして使用できます。In addition to the conditional directives already discussed, the @isset and @empty directives may be used as convenient shortcuts for their respective PHP functions:

@isset($records)
    // $recordsは定義済みでnullでない
@endisset

@empty($records)
    // $recordsが「空」だ
@endempty

認証ディレクティブAuthentication Directives

@auth@guestディレクティブは、現在のユーザーが認証されているか、もしくはゲストであるかを簡単に判定するために使用します。The @auth and @guest directives may be used to quickly determine if the current user is authenticated or is a guest:

@auth
    // ユーザーは認証済み
@endauth

@guest
    // ユーザーは認証されていない
@endguest

必要であれば、@auth@guestディレクティブ使用時に、確認すべき認証ガードを指定できます。If needed, you may specify the authentication guard[/docs/{{version}}/authentication] that should be checked when using the @auth and @guest directives:

@auth('admin')
    // ユーザーは認証済み
@endauth

@guest('admin')
    // ユーザーは認証されていない
@endguest

セクションディレクティブSection Directives

セクションがコンテンツを持っているかを判定したい場合は、@hasSectionディレクティブを使用します。You may check if a section has content using the @hasSection directive:

@hasSection('navigation')
    <div class="pull-right">
        @yield('navigation')
    </div>

    <div class="clearfix"></div>
@endif

セクションに何か内容が含まれているかを判定するために、@sectionMissingディレクティブが使用できます。You may use the sectionMissing directive to determine if a section does not have content:

@sectionMissing('navigation')
    <div class="pull-right">
        @include('default-navigation')
    </div>
@endif

環境ディレクティブEnvironment Directives

アプリケーションが実働環境("production")で実行されているかを調べるには、@productionディレクティブを使います。You may check if the application is running in the production environment using the @production directive:

@production
    // 実働環境のコンテンツを指定…
@endproduction

もしくは、特定の環境でアプリケーションが実行されているかを判定するには、@envディレクティブを使います。Or, you may determine if the application is running in a specific environment using the @env directive:

@env('staging')
    // アプリケーションが"staging"環境で実行中
@endenv

@env(['staging', 'production'])
    // アプリケーションが"staging"と"production"環境で実行中
@endenv

Switch文Switch Statements

@switch@case@break@default@endswitchディレクティブを使用し、switch文を構成できます。Switch statements can be constructed using the @switch, @case, @break, @default and @endswitch directives:

@switch($i)
    @case(1)
        最初のケース
        @break

    @case(2)
        2番めのケース
        @break

    @default
        デフォルトのケース
@endswitch

繰り返しLoops

条件文に加え、BladeはPHPがサポートしている繰り返し構文も提供しています。これらも、対応するPHP構文と使い方は一緒です。In addition to conditional statements, Blade provides simple directives for working with PHP's loop structures. Again, each of these directives functions identically to their PHP counterparts:

@for ($i = 0; $i < 10; $i  )
    現在の値は: {{ $i }}
@endfor

@foreach ($users as $user)
    <p>これは {{ $user->id }} ユーザーです。</p>
@endforeach

@forelse ($users as $user)
    <li>{{ $user->name }}</li>
@empty
    <p>ユーザーなし</p>
@endforelse

@while (true)
    <p>無限ループ中</p>
@endwhile

lightbulb">Tip!! 繰り返し中はループ変数を使い、繰り返しの最初や最後なのかなど、繰り返し情報を取得できます。{tip} When looping, you may use the loop variable[#the-loop-variable] to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop.

繰り返しを使用する場合、ループを終了するか、現在の繰り返しをスキップすることもできます。When using loops you may also end the loop or skip the current iteration:

@foreach ($users as $user)
    @if ($user->type == 1)
        @continue
    @endif

    <li>{{ $user->name }}</li>

    @if ($user->number == 5)
        @break
    @endif
@endforeach

もしくは、ディレクティブに条件を記述して、一行で済ますこともできます。You may also include the condition with the directive declaration in one line:

@foreach ($users as $user)
    @continue($user->type == 1)

    <li>{{ $user->name }}</li>

    @break($user->number == 5)
@endforeach

ループ変数The Loop Variable

繰り返し中は、$loop変数が使用できます。この変数により、現在のループインデックスや繰り返しの最初/最後なのかなど、便利な情報にアクセスできます。When looping, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop:

@foreach ($users as $user)
    @if ($loop->first)
        これは最初の繰り返し
    @endif

    @if ($loop->last)
        これは最後の繰り返し
    @endif

    <p>これは {{ $user->id }} ユーザーです。</p>
@endforeach

ネストした繰り返しでは、親のループの$loop変数にparentプロパティを通じアクセスできます。If you are in a nested loop, you may access the parent loop's $loop variable via the parent property:

@foreach ($users as $user)
    @foreach ($user->posts as $post)
        @if ($loop->parent->first)
            これは親のループの最初の繰り返しだ
        @endif
    @endforeach
@endforeach

$loop変数は、他にもいろいろと便利なプロパティを持っています。The $loop variable also contains a variety of other useful properties:

プロパティProperty 説明Description
$loop->index$loop->index 現在のループのインデックス(初期値0)The index of the current loop iteration (starts at 0).
$loop->iteration$loop->iteration 現在の繰り返し数(初期値1)The current loop iteration (starts at 1).
$loop->remaining$loop->remaining 繰り返しの残り数The iterations remaining in the loop.
$loop->count$loop->count 繰り返し中の配列の総アイテム数The total number of items in the array being iterated.
$loop->first$loop->first ループの最初の繰り返しか判定Whether this is the first iteration through the loop.
$loop->last$loop->last ループの最後の繰り返しか判定Whether this is the last iteration through the loop.
$loop->even$loop->even これは偶数回目の繰り返しか判定Whether this is an even iteration through the loop.
$loop->odd$loop->odd これは奇数回目の繰り返しか判定Whether this is an odd iteration through the loop.
$loop->depth$loop->depth 現在のループのネストレベルThe nesting level of the current loop.
$loop->parent$loop->parent ループがネストしている場合、親のループ変数When in a nested loop, the parent's loop variable.

コメントComments

Bladeでビューにコメントを書くこともできます。HTMLコメントと異なり、Bladeのコメントはアプリケーションから返されるHTMLには含まれません。Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application:

{{-- このコメントはレンダー後のHTMLには現れない --}}

PHPPHP

PHPコードをビューへ埋め込むと便利な場合もあります。Bladeの@phpディレクティブを使えば、テンプレートの中でプレーンなPHPブロックを実行できます。In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template:

@php
    //
@endphp

lightbulb">Tip!! Bladeはこの機能を提供していますが、数多く使用しているのであれば、それはテンプレートへ多すぎるロジックを埋め込んでいるサインです。{tip} While Blade provides this feature, using it frequently may be a signal that you have too much logic embedded within your template.

@onceディレクティブThe @once Directive

@onceディレクティブは、レンダリングサイクルごとに一度だけ評価されるテンプレートの一部を定義できます。これはstacksを使い、JavaScriptをページのヘッダへ挿入するのに便利です。たとえば、ループ内で与えられた コンポーネントをレンダリングしている場合、最初にコンポーネントがレンダリングされたときのみ、JavaScriptをヘッダにプッシュできます。The @once directive allows you to define a portion of the template that will only be evaluate once per rendering cycle. This may be useful for pushing a given piece of JavaScript into the page's header using stacks[#stacks]. For example, if you are rendering a given component[#components] within a loop, you may wish to only push the JavaScript to the header the the first time the component is rendered:

@once
    @push('scripts')
        <script>
            // カスタムJavaScriptコード…
        </script>
    @endpush
@endonce

フォームForms

CSRFフィールドCSRF Field

アプリケーションでHTMLフォームを定義する場合、CSRF保護ミドルウェアがリクエストを検査できるようにするため、隠しCSRFトークンフィールドを含める必要があります。このトークンフィールドを生成するには、@csrf Bladeディレクティブを使用します。Anytime you define an HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection[https://laravel.com/docs/{{version}}/csrf] middleware can validate the request. You may use the @csrf Blade directive to generate the token field:

<form method="POST" action="/profile">
    @csrf

    ...
</form>

MethodフィールドMethod Field

HTMLフォームでは、PUTPATCHDELETEリクエストを作成できないため、見かけ上のHTTP動詞を指定するための_methodフィールドを追加する必要があります。@method Bladeディレクティブでこのフィールドを生成できます。Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The @method Blade directive can create this field for you:

<form action="/foo/bar" method="POST">
    @method('PUT')

    ...
</form>

バリデーションエラーValidation Errors

@errorディレクティブは、指定した属性のバリデーションエラーメッセージがあるかを簡単に判定するために使用します。@errorディレクティブの中でエラーメッセージを表示するために、$message変数をエコーすることも可能です。The @error directive may be used to quickly check if validation error messages[/docs/{{version}}/validation#quick-displaying-the-validation-errors] exist for a given attribute. Within an @error directive, you may echo the $message variable to display the error message:

<!-- /resources/views/post/create.blade.php -->

<label for="title">Post Title</label>

<input id="title" type="text" class="@error('title') is-invalid @enderror">

@error('title')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

複数のフォームにより構成されたページで、バリデーションエラーを取得するために、@errorディレクティブの第2引数として特定のエラーバッグの名前が渡せます。You may pass the name of a specific error bag[/docs/{{version}}/validation#named-error-bags] as the second parameter to the @error directive to retrieve validation error messages on pages containing multiple forms:

<!-- /resources/views/auth.blade.php -->

<label for="email">Email address</label>

<input id="email" type="email" class="@error('email', 'login') is-invalid @enderror">

@error('email', 'login')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror

コンポーネントComponents

コンポーネントとスロットは、レイアウトとセクションに似た利便性をもたらします。ですがコンポーネントとスロットのほうが簡単に理解できるメンタルモデルであるとわかってもらえるでしょう。コンポーネントを書くには2つのアプローチがあります。クラスベースコンポーネントと匿名コンポーネントです。Components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. There are two approaches to writing components: class based components and anonymous components.

make:component Artisanコマンドを使えば、クラスベースのコンポーネントを生成できます。コンポーネントの使い方を説明するために、簡単なAlertコンポーネントを作成してみましょう。make:componentコマンドはApp\View\Componentsディレクトリの中にコンポーネントを生成します。To create a class based component, you may use the make:component Artisan command. To illustrate how to use components, we will create a simple Alert component. The make:component command will place the component in the App\View\Components directory:

php artisan make:component Alert

make:componentコマンドは、コンポーネントのためのビューテンプレートも生成します。このビューはresources/views/componentsディレクトリに生成されます。The make:component command will also create a view template for the component. The view will be placed in the resources/views/components directory.

パッケージコンポーネントの登録Manually Registering Package Components

アプリケーションのために書いたコンポーネントは、自動的にapp/View/Componentsresources/views/componentsディレクトリの中で見つけられます。When writing components for your own application, components are automatically discovered within the app/View/Components directory and resources/views/components directory.

しかしながら、Bladeコンポーネントを活用したパッケージを構築している場合、コンポーネントクラスとそのHTMLタグエイリアスを皆さん自身で登録する必要があります。通常、皆さんのパッケージのサービスプロバイダ内にあるbootメソッドで、コンポーネントを登録する必要があります。However, if you are building a package that utilizes Blade components, you will need to manually register your component class and its HTML tag alias. You should typically register your components in the boot method of your package's service provider:

use Illuminate\Support\Facades\Blade;

/**
 * パッケージのサービスの初期処理
 */
public function boot()
{
    Blade::component('package-alert', AlertComponent::class);
}

コンポーネントを登録したら、そのタグエイリアスを使用してレンダーします。Once your component has been registered, it may be rendered using its tag alias:

<x-package-alert/>

コンポーネントの表示Displaying Components

コンポーネントを表示するには、Bladeテンプレートの中でBladeコンポーネントタグを使用します。Bladeコンポーネントタグとは、コンポーネントクラス名のケバブケースをx-に続けた文字列のことです。To display a component, you may use a Blade component tag within one of your Blade templates. Blade component tags start with the string x- followed by the kebab case name of the component class:

<x-alert/>

<x-user-profile/>

App\View\Componentsディレクトリの中にコンポーネントクラスをネストしている場合は、ディレクトリのネストを表すために.を使います。たとえばApp\View\Components\Inputs\Button.phpがコンポーネントだとすると、次のようにレンダーします。If the component class is nested deeper within the App\View\Components directory, you may use the . character to indicate directory nesting. For example, if we assume a component is located at App\View\Components\Inputs\Button.php, we may render it like so:

<x-inputs.button/>

コンポーネントへのデータ渡しPassing Data To Components

HTML属性を使い、Bladeコンポーネントへデータを渡すことができます。シンプルなHTML属性を使い、ハードコードしたプリミティブ値をコンポーネントへ渡します。PHP表現と変数は、:を前に付けた属性によりコンポーネントへ渡します。You may pass data to Blade components using HTML attributes. Hard-coded, primitive values may be passed to the component using simple HTML attributes. PHP expressions and variables should be passed to the component via attributes that are prefixed with ::

<x-alert type="error" :message="$message"/>

コンポーネントで必須のデータは、クラスのコンストラクタで定義する必要があります。コンポーネント上のパブリックプロパティはすべて、コンポーネントのビューで自動的に使えます。コンポーネントのrenderメソッドからビューへデータを渡す必要はありません。You should define the component's required data in its class constructor. All public properties on a component will automatically be made available to the component's view. It is not necessary to pass the data to the view from the component's render method:

<?php

namespace App\View\Components;

use Illuminate\View\Component;

class Alert extends Component
{
    /**
     * alertのタイプ
     *
     * @var string
     */
    public $type;

    /**
     * alertのメッセージ
     *
     * @var string
     */
    public $message;

    /**
     * コンポーネントインスタンスの生成
     *
     * @param  string  $type
     * @param  string  $message
     * @return void
     */
    public function __construct($type, $message)
    {
        $this->type = $type;
        $this->message = $message;
    }

    /**
     * コンポーネントを表すビュー/コンテンツの取得
     *
     * @return \Illuminate\View\View|\Closure|string
     */
    public function render()
    {
        return view('components.alert');
    }
}

コンポーネントがレンダーされるときに、名前が一致するコンポーネントのパブリック変数がエコーされることにより、コンテンツは表示されます。When your component is rendered, you may display the contents of your component's public variables by echoing the variables by name:

<div class="alert alert-{{ $type }}">
    {{ $message }}
</div>

キャストCasing

コンポーネントのコンストラクタ引数はキャメルケース(camelCase)を使用し、HTML属性の中で引数名を参照するときはケバブケース(kebab-case)を使用します。たとえば、以下のようなコンポーネントコンストラクタがあったとしましょう。Component constructor arguments should be specified using camelCase, while kebab-case should be used when referencing the argument names in your HTML attributes. For example, given the following component constructor:

/**
 * コンポーネントインスタンスの生成
 *
 * @param  string  $alertType
 * @return void
 */
public function __construct($alertType)
{
    $this->alertType = $alertType;
}

$alertType引数は以下のように指定します。The $alertType argument may be provided like so:

<x-alert alert-type="danger" />

コンポーネントメソッドComponent Methods

コンポーネントテンプレートではパブリックな変数が使えるのに加え、コンポーネントの全パブリックメソッドも実行可能です。たとえば、コンポーネントにisSelectedメソッドがあると想像してください。In addition to public variables being available to your component template, any public methods on the component may also be executed. For example, imagine a component that has a isSelected method:

/**
 * 指定されたオプションが現在選ばれているか判定する
 *
 * @param  string  $option
 * @return bool
 */
public function isSelected($option)
{
    return $option === $this->selected;
}

メソッド名と一致する変数を呼び出せば、コンポーネントテンプレートからこのメソッドを実行できます。You may execute this method from your component template by invoking the variable matching the name of the method:

<option {{ $isSelected($value) ? 'selected="selected"' : '' }} value="{{ $value }}">
    {{ $label }}
</option>

クラス内での属性/スロットの使用Using Attributes & Slots Inside The Class

Bladeコンポーネントはクラスのrenderメソッドの中からコンポーネント名、属性、スロットへアクセスできます。しかし、このデータにアクセスするにはコンポーネントのrenderメソッドからクロージャを返す必要があります。クロージャは唯一の引数として$data配列を受け取ります。Blade components also allow you to access the component name, attributes, and slot inside the class's render method. However, in order to access this data, you should return a Closure from your component's render method. The Closure will receive a $data array as its only argument:

/**
 * コンポーネントを表すビュー/内容の取得
 *
 * @return \Illuminate\View\View|\Closure|string
 */
public function render()
{
    return function (array $data) {
        // $data['componentName'];
        // $data['attributes'];
        // $data['slot'];

        return '<div>Component content</div>';
    };
}

componentNameは、HTMLタグ中でx-プレフィックスに続けて使用している名前と同じです。そのため、<x-alert />componentNamealertとなります。attributes要素はHTMLタグ中に現れるすべての属性を含みます。slot要素はそのコンポーネントのスロットの内容のIlluminate\Support\HtmlStringインスタンスです。The componentName is equal to the name used in the HTML tag after the x- prefix. So <x-alert />'s componentName will be alert. The attributes element will contain all of the attributes that were present on the HTML tag. The slot element is a Illuminate\Support\HtmlString instance with the contents of the slot from the component.

依存の追加Additional Dependencies

コンポーネントがLaravelのサービスコンテナからの依存注入を必要としているなら、コンポーネントのデータ属性の前に依存をリストしておけば、コンテナにより自動的に注入されます。If your component requires dependencies from Laravel's service container[/docs/{{version}}/container], you may list them before any of the component's data attributes and they will automatically be injected by the container:

use App\AlertCreator

/**
 * コンポーネントインスタンスの生成
 *
 * @param  \App\AlertCreator  $creator
 * @param  string  $type
 * @param  string  $message
 * @return void
 */
public function __construct(AlertCreator $creator, $type, $message)
{
    $this->creator = $creator;
    $this->type = $type;
    $this->message = $message;
}

属性の管理Managing Attributes

コンポーネントへデータ属性を渡す方法はすでに説明しました。しかしながら、たとえばコンポーネントが機能するためには必須でないデータであるclassのような、追加のHTML属性を指定する必要も起き得ます。コンポーネントテンプレートのルート要素へ追加の属性を渡したい場合が、典型例でしょう。例として、alertコンポーネントを次のようにレンダーするのを想像してください。We've already examined how to pass data attributes to a component; however, sometimes you may need to specify additional HTML attributes, such as class, that are not part of the data required for a component to function. Typically, you want to pass these additional attributes down to the root element of the component template. For example, imagine we want to render an alert component like so:

<x-alert type="error" :message="$message" class="mt-4"/>

コンポーネントのコンストラクタで依存していしていない残りの属性すべては、そのコンポーネントの「属性バッグ」へ追加されます。この属性バッグは$attributes変数によりコンポーネントで使用可能になります。この変数をエコーすることにより、コンポーネント中ですべての属性がレンダーされます。All of the attributes that are not part of the component's constructor will automatically be added to the component's "attribute bag". This attribute bag is automatically made available to the component via the $attributes variable. All of the attributes may be rendered within the component by echoing this variable:

<div {{ $attributes }}>
    <!-- コンポーネントのコンテンツ -->
</div>

Note: note コンポーネントでの変数({{ $attributes }})の表示や、@envディレクティブの使用は、今のところサポートしていません。{note} Echoing variables ({{ $attributes }}) or using directives such as @env directly on a component is not supported at this time.

デフォルト/属性のマージDefault / Merged Attributes

属性にデフォルト値を指定、またはコンポーネントの属性へ追加の値をマージする必要も時に起きます。これには属性バッグのmergeメソッドを使用します。Sometimes you may need to specify default values for attributes or merge additional values into some of the component's attributes. To accomplish this, you may use the attribute bag's merge method:

<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
    {{ $message }}
</div>

このコンポーネントを次のように使用すると仮定してみましょう。If we assume this component is utilized like so:

<x-alert type="error" :message="$message" class="mb-4"/>

最終的にこのコンポーネントは、以下のようなHTMLでレンダーされます。The final, rendered HTML of the component will appear like the following:

<div class="alert alert-error mb-4">
    <!-- ここには$message変数の内容がレンダーされる -->
</div>

属性のフィルタリングFiltering Attributes

filterメソッドを使い、属性をフィルタリングできます。このメソッドはクロージャを引数に取り、属性バックの中へ残す属性に対しtrueを返してください。You may filter attributes using the filter method. This method accepts a Closure which should return true if you wish to retain the attribute in the attribute bag:

{{ $attributes->filter(fn ($value, $key) => $key == 'foo') }}

より便利に使うため、指定文字列から始まるキー名の属性を全部取得する、whereStartsWithメソッドを使うことも可能です。For convenience, you may use the whereStartsWith method to retrieve all attributes whose keys begin with a given string:

{{ $attributes->whereStartsWith('wire:model') }}

firstメソッドを使い、指定した属性バッグの中の最初の属性をレンダーすることもできます。Using the first method, you may render the first attribute in a given attribute bag:

{{ $attributes->whereStartsWith('wire:model')->first() }}

スロットSlots

コンポーネントに「スロット」を使用して、追加のコンテンツを渡す必要性がしばしばあると思います。次のようなaleatコンポーネントを作ったとイメージしてください。Often, you will need to pass additional content to your component via "slots". Let's imagine that an alert component we created has the following markup:

<!-- /resources/views/components/alert.blade.php -->

<div class="alert alert-danger">
    {{ $slot }}
</div>

コンポーネントにコンテンツを挿入することにより、slotに内容を渡せます。We may pass content to the slot by injecting content into the component:

<x-alert>
    <strong>あーーー!</strong> なんか変だ!
</x-alert>

コンポーネント中の別々の場所に、複数の別々なスロットをレンダーする必要も起きるでしょう。ではalertコンポーネントへ"title"を挿入できるように変更してみましょう。Sometimes a component may need to render multiple different slots in different locations within the component. Let's modify our alert component to allow for the injection of a "title":

<!-- /resources/views/components/alert.blade.php -->

<span class="alert-title">{{ $title }}</span>

<div class="alert alert-danger">
    {{ $slot }}
</div>

x-slotタグを使い、名前付きスロットのコンテンツを定義します。x-slotの外のコンテンツは、すべて$slot変数によりコンポーネントへ渡されます。You may define the content of the named slot using the x-slot tag. Any content not within a x-slot tag will be passed to the component in the $slot variable:

<x-alert>
    <x-slot name="title">
        サーバエラー
    </x-slot>

    <strong>Whoops!</strong> Something went wrong!
</x-alert>

スコープ付きスロットScoped Slots

VueのようなJavaScriptフレームワークを使用している方は「スコープ付きスロット」に慣れていると思います。これは、スロットの中でコンポーネントのデータやメソッドへアクセスできる機構です。同様の振る舞いはLaravelでも、コンポーネントでpublicメソッドやプロパティを定義すれば可能です。component変数によりスロットの中でコンポーネントへアクセスします。If you have used a JavaScript framework such as Vue, you may be familiar with "scoped slots", which allow you to access data or methods from the component within your slot. You may achieve similar behavior in Laravel by defining public methods or properties on your component and accessing the component within your slot via the $component variable:

<x-alert>
    <x-slot name="title">
        {{ $component->formatAlert('Server Error') }}
    </x-slot>

    <strong>あーーー!</strong> なんか変だ!
</x-alert>

インラインコンポーネントビューInline Component Views

小さなコンポーネントでは、コンポーネントクラスとコンポーネントのビューテンプレート両方を管理するのは面倒に感じるでしょう。そのため、コンポーネントのマークアップを直接renderメソッドから返せます。For very small components, it may feel cumbersome to manage both the component class and the component's view template. For this reason, you may return the component's markup directly from the render method:

/**
 * コンポーネントを表すビュー/コンテンツの取得
 *
 * @return \Illuminate\View\View|\Closure|string
 */
public function render()
{
    return <<<'blade'
        <div class="alert alert-danger">
            {{ $slot }}
        </div>
    blade;
}

インラインビューコンポーネントの生成Generating Inline View Components

インラインビューをレンダーするコンポーネントを生成するには、make:componentコマンド実行時にinlineオプションを使用します。To create a component that renders an inline view, you may use the inline option when executing the make:component command:

php artisan make:component Alert --inline

無名コンポーネントAnonymous Components

インラインコンポーネントと同様に、一つのファイルでコンポーネントを管理する仕組みを提供しているのが、無名コンポーネントです。違いは、無名コンポーネントは一つのビューファイルを使用し、関係するクラスはありません。無名コンポーネントを定義するには、resources/views/componentsディレクトリの中にBladeテンプレートを設置する必要があります。ここではresources/views/components/alert.blade.phpにコンポーネントを定義すると仮定しましょう。Similar to inline components, anonymous components provide a mechanism for managing a component via a single file. However, anonymous components utilize a single view file and have no associated class. To define an anonymous component, you only need to place a Blade template within your resources/views/components directory. For example, assuming you have defined a component at resources/views/components/alert.blade.php:

<x-alert/>

componentsディレクトリ下にネストしたサブディレクトリ中へコンポーネントを設置する場合は、.を使ってください。たとえば、resources/views/components/inputs/button.blade.phpへ定義する場合、次のようになります。You may use the . character to indicate if a component is nested deeper inside the components directory. For example, assuming the component is defined at resources/views/components/inputs/button.blade.php, you may render it like so:

<x-inputs.button/>

データプロパティ/属性Data Properties / Attributes

無名コンポーネントには関連するクラスがないため、どのデータが変数を通じてコンポーネントへ渡され、どの属性がコンポーネントの属性バッグに入れられるのかの違いに迷うと思います。Since anonymous components do not have any associated class, you may wonder how you may differentiate which data should be passed to the component as variables and which attributes should be placed in the component's attribute bag[#managing-attributes].

コンポーネントのBladeテンプレートの先頭で@propsディレクティブを使い、データ変数としてどの属性を取り扱うかを指定します。コンポーネント中の他の属性は、属性バッグを使い利用可能です。データ変数にデフォルト値を指定する場合は、変数の名前を配列キーとして指定し、デフォルト値を配列値として指定します。You may specify which attributes should be considered data variables using the @props directive at the top of your component's Blade template. All other attributes on the component will be available via the component's attribute bag. If you wish to give a data variable a default value, you may specify the variable's name as the array key and the default value as the array value:

<!-- /resources/views/components/alert.blade.php -->

@props(['type' => 'info', 'message'])

<div {{ $attributes->merge(['class' => 'alert alert-'.$type]) }}>
    {{ $message }}
</div>

サブビューの読み込みIncluding Subviews

Bladeの@includeディレクディブを使えば、ビューの中から簡単に他のBladeビューを取り込めます。読み込み元のビューで使用可能な変数は、取り込み先のビューでも利用可能です。Blade's @include directive allows you to include a Blade view from within another view. All variables that are available to the parent view will be made available to the included view:

<div>
    @include('shared.errors')

    <form>
        <!-- フォームの内容 -->
    </form>
</div>

親のビューの全データ変数が取り込み先のビューに継承されますが、追加のデータも配列で渡すことができます。Even though the included view will inherit all data available in the parent view, you may also pass an array of extra data to the included view:

@include('view.name', ['some' => 'data'])

存在しないビューを@includeすれば、Laravelはエラーを投げます。存在しているかどうかわからないビューを取り込みたい場合は、@includeIfディレクティブを使います。If you attempt to @include a view which does not exist, Laravel will throw an error. If you would like to include a view that may or may not be present, you should use the @includeIf directive:

@includeIf('view.name', ['some' => 'data'])

指定した論理条件がtrueの場合に@includeしたい場合は、@includeWhenディレクティブを使用します。If you would like to @include a view if a given boolean expression evaluates to true, you may use the @includeWhen directive:

@includeWhen($boolean, 'view.name', ['some' => 'data'])

指定した論理条件がfalseの場合に@includeしたい場合は、@includeUnlessディレクティブを使用します。If you would like to @include a view if a given boolean expression evaluates to false, you may use the @includeUnless directive:

@includeUnless($boolean, 'view.name', ['some' => 'data'])

指定するビューの配列から、最初に存在するビューを読み込むには、includeFirstディレクティブを使用します。To include the first view that exists from a given array of views, you may use the includeFirst directive:

@includeFirst(['custom.admin', 'admin'], ['some' => 'data'])

Note: note Bladeビューの中では__DIR____FILE__を使わないでください。キャッシュされたコンパイル済みのビューのパスが返されるからです。{note} You should avoid using the __DIR__ and __FILE__ constants in your Blade views, since they will refer to the location of the cached, compiled view.

サブビューのエイリアスAliasing Includes

Bladeのサブビューがサブディレクトリへ設置されている場合でも簡潔にアクセスできるよう、エイリアスを使用できます。たとえば、以下の内容のBladeサブビューが、resources/views/includes/input.blade.phpへ保存されていると想像してください。If your Blade includes are stored in a subdirectory, you may wish to alias them for easier access. For example, imagine a Blade include that is stored at resources/views/includes/input.blade.php with the following content:

<input type="{{ $type ?? 'text' }}">

includes.inputへのinputエイリアスを設定するには、includeメソッドを使用します。通常これは、AppServiceProviderbootメソッドの中で行うべきです。You may use the include method to alias the include from includes.input to input. Typically, this should be done in the boot method of your AppServiceProvider:

use Illuminate\Support\Facades\Blade;

Blade::include('includes.input', 'input');

サブビューのエイリアスを設定したら、Bladeディレクティブとして、そのエイリアス名を使用することにより、レンダーされます。Once the include has been aliased, you may render it using the alias name as the Blade directive:

@input(['type' => 'email'])

コレクションのレンダービューRendering Views For Collections

Bladeの@eachディレクティブを使い、ループとビューの読み込みを組み合わせられます。You may combine loops and includes into one line with Blade's @each directive:

@each('view.name', $jobs, 'job')

最初の引数は配列かコレクションの各要素をレンダーするための部分ビューです。第2引数は繰り返し処理する配列かコレクションで、第3引数はビューの中の繰り返し値が代入される変数名です。ですから、たとえばjobs配列を繰り返す場合なら、部分ビューの中で各ジョブにはjob変数としてアクセスしたいと通常は考えるでしょう。 現在の繰り返しのキーは、部分ビューの中のkey変数で参照できます。The first argument is the view partial to render for each element in the array or collection. The second argument is the array or collection you wish to iterate over, while the third argument is the variable name that will be assigned to the current iteration within the view. So, for example, if you are iterating over an array of jobs, typically you will want to access each job as a job variable within your view partial. The key for the current iteration will be available as the key variable within your view partial.

@eachディレクティブには第4引数を渡たせます。この引数は配列が空の場合にレンダーされるビューを指定します。You may also pass a fourth argument to the @each directive. This argument determines the view that will be rendered if the given array is empty.

@each('view.name', $jobs, 'job', 'view.empty')

Note: note @eachを使ってレンダーされるビューは、親のビューから変数を継承しません。子ビューで親ビューの変数が必要な場合は、代わりに@foreach@includeを使用してください。{note} Views rendered via @each do not inherit the variables from the parent view. If the child view requires these variables, you should use @foreach and @include instead.

スタックStacks

Bladeはさらに、他のビューやレイアウトでレンダーできるように、名前付きのスタックへ内容を退避できます。子ビューで必要なJavaScriptを指定する場合に、便利です。Blade allows you to push to named stacks which can be rendered somewhere else in another view or layout. This can be particularly useful for specifying any JavaScript libraries required by your child views:

@push('scripts')
    <script src="/example.js"></script>
@endpush

必要なだけ何回もスタックをプッシュできます。スタックした内容をレンダーするには、@stackディレクティブにスタック名を指定してください。You may push to a stack as many times as needed. To render the complete stack contents, pass the name of the stack to the @stack directive:

<head>
    <!-- Headの内容 -->

    @stack('scripts')
</head>

スタックの先頭に内容を追加したい場合は、@prependディレクティブを使用してください。If you would like to prepend content onto the beginning of a stack, you should use the @prepend directive:

@push('scripts')
    ここは2番目
@endpush

// …後から

@prepend('scripts')
    ここは最初
@endprepend

サービス注入Service Injection

@injectディレクティブはLaravelのサービスコンテナからサービスを取得するために使用します。@injectの最初の引数はそのサービスを取り込む変数名で、第2引数は依存解決したいクラス/インターフェイス名です。The @inject directive may be used to retrieve a service from the Laravel service container[/docs/{{version}}/container]. The first argument passed to @inject is the name of the variable the service will be placed into, while the second argument is the class or interface name of the service you wish to resolve:

@inject('metrics', 'App\Services\MetricsService')

<div>
    Monthly Revenue: {{ $metrics->monthlyRevenue() }}.
</div>

Blade拡張Extending Blade

Bladeではdirectiveメソッドを使い、自分のカスタムディレクティブを定義できます。Bladeコンパイラがそのカスタムディレクティブを見つけると、そのディレクティブに渡される引数をコールバックへの引数として呼び出します。Blade allows you to define your own custom directives using the directive method. When the Blade compiler encounters the custom directive, it will call the provided callback with the expression that the directive contains.

次の例は@datetime($var)ディレクティブを作成し、渡されるDateTimeインスタンスの$varをフォーマットします。The following example creates a @datetime($var) directive which formats a given $var, which should be an instance of DateTime:

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * 全アプリケーションサービスの登録
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * アプリケーションの全サービスの初期処理
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function ($expression) {
            return "<?php echo ($expression)->format('m/d/Y H:i'); ?>";
        });
    }
}

ご覧の通り、ディレクティブがどんなものであれ、渡された引数にformatメソッドをチェーンし、呼び出しています。そのため、この例のディレクティブの場合、最終的に生成されるPHPコードは、次のようになります。As you can see, we will chain the format method onto whatever expression is passed into the directive. So, in this example, the final PHP generated by this directive will be:

<?php echo ($var)->format('m/d/Y H:i'); ?>

Note: note Bladeディレクティブのロジックを更新した後に、Bladeビューのキャッシュを全部削除する必要があります。view:clear Artisanコマンドで、キャッシュされているBladeビューを削除できます。{note} After updating the logic of a Blade directive, you will need to delete all of the cached Blade views. The cached Blade views may be removed using the view:clear Artisan command.

カスタムif文Custom If Statements

シンプルなカスタム条件文を定義する時、必要以上にカスタムディレクティブのプログラミングが複雑になってしまうことが、ときどき起きます。そのため、Bladeはクロージャを使用し、カスタム条件ディレクティブを素早く定義できるように、Blade::ifメソッドを提供しています。例として、現在のアプリケーションのクラウドプロバイダをチェックするカスタム条件を定義してみましょう。AppServiceProviderbootメソッドで行います。Programming a custom directive is sometimes more complex than necessary when defining simple, custom conditional statements. For that reason, Blade provides a Blade::if method which allows you to quickly define custom conditional directives using Closures. For example, let's define a custom conditional that checks the current application cloud provider. We may do this in the boot method of our AppServiceProvider:

use Illuminate\Support\Facades\Blade;

/**
 * 全アプリケーションサービスの初期起動
 *
 * @return void
 */
public function boot()
{
    Blade::if('cloud', function ($provider) {
        return config('filesystems.default') === $provider;
    });
}

カスタム条件を定義したら、テンプレートの中で簡単に利用できます。Once the custom conditional has been defined, we can easily use it on our templates:

@cloud('digitalocean')
    // アプリケーションはdigitaloceanクラウドプロバイダを使用している
@elsecloud('aws')
    // アプリケーションはawsプロバイダを使用している
@else
    // アプリケーションはdigitaloceanとawsプロバイダを使用していない
@endcloud

@unlesscloud('aws')
    // アプリケーションはawsプロバイダを使用していない
@endcloud

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作