Readouble

Laravel 5.8 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');
});

コンポーネントとスロットComponents & Slots

コンポーネントとスロットは、セクションとレイアウトと似た利便を提供します。しかし、コンポーネントとスロットのメンタルモデルのほうが簡単に理解できることに気づくはずです。最初に、アプリケーション全体で再利用する、"alert"コンポーネントをイメージしてください。Components and slots provide similar benefits to sections and layouts; however, some may find the mental model of components and slots easier to understand. First, let's imagine a reusable "alert" component we would like to reuse throughout our application:

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

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

{{ $slot }}変数は、このコンポーネントへ注入しようとする内容を含んでいます。では、このコンポーネントを構築するため、@component Bladeディレクティブを使いましょう。The {{ $slot }} variable will contain the content we wish to inject into the component. Now, to construct this component, we can use the @component Blade directive:

@component('alert')
    <strong>Whoops!</strong> Something went wrong!
@endcomponent

そのコンポーネントへ利用する可能性があるビューの配列を指定し、存在する最初のビューをロードするようにLaravelへ指示するには、componentFirstディレクティブを使用してください。To instruct Laravel to load the first view that exists from a given array of possible views for the component, you may use the componentFirst directive:

@componentFirst(['custom.alert', 'alert'])
    <strong>Whoops!</strong> Something went wrong!
@endcomponent

一つのコンポーネントに対し、複数のスロットを定義するのも、役立つことがあるでしょう。"title"を注入できるようにalertコンポーネントを改造してみましょう。名前付きスロットは、名前に一致する変数を"echo"します。Sometimes it is helpful to define multiple slots for a component. Let's modify our alert component to allow for the injection of a "title". Named slots may be displayed by "echoing" the variable that matches their name:

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

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

    {{ $slot }}
</div>

これで、@slotディレクティブを使い、名前付きスロットへ内容を注入できます。@slotディレクティブ範囲外の全内容は、$slot変数の中のコンポーネントへ渡されます。Now, we can inject content into the named slot using the @slot directive. Any content not within a @slot directive will be passed to the component in the $slot variable:

@component('alert')
    @slot('title')
        Forbidden
    @endslot

    You are not allowed to access this resource!
@endcomponent

コンポーネントへ追加のデータを渡すPassing Additional Data To Components

場合により、コンポーネントへ追加のデータを渡す必要が起きます。そのため、@componentディレクティブの第2引数で、データの配列が渡せます。全データはテンプレート中で変数として利用できます。Sometimes you may need to pass additional data to a component. For this reason, you can pass an array of data as the second argument to the @component directive. All of the data will be made available to the component template as variables:

@component('alert', ['foo' => 'bar'])
    ...
@endcomponent

コンポーネントの別名Aliasing Components

Bladeコンポーネントをサブディレクトリへ保存している場合、簡単にアクセスできるようにエイリアスを使いたくなります。たとえば、resources/views/components/alert.blade.phpへBladeコンポーネントを保存していると想像してください。componentメソッドを使い、components.alertコンポーネントの別名をalertと名付けられます。通常、AppServiceProviderbootメソッドで別名を指定します。If your Blade components are stored in a sub-directory, you may wish to alias them for easier access. For example, imagine a Blade component that is stored at resources/views/components/alert.blade.php. You may use the component method to alias the component from components.alert to alert. Typically, this should be done in the boot method of your AppServiceProvider:

use Illuminate\Support\Facades\Blade;

Blade::component('components.alert', 'alert');

コンポーネントへ別名を付けたら、ディレクティブでレンダできます。」Once the component has been aliased, you may render it using a directive:

@alert(['type' => 'danger'])
    You are not allowed to access this resource!
@endalert

追加のスロットがなければ、コンポーネントの引数を省略できます。You may omit the component parameters if it has no additional slots:

@alert
    You are not allowed to access this resource!
@endalert

データ表示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.

@jsonディレクティブは、Vueコンポーネントやdata-*属性を生成するのにも便利に使えます。The @json directive is also useful for seeding Vue components or data-* attributes:

<example-component :some-prop='@json($array)'></example-component>

Note: note 要素の属性の中で@jsonを使用する場合は、シングルコーテーションで囲みます。{note} Using @json in element attributes requires that it be surrounded by single quotes.

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.

@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

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.

フォーム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

サブビューの読み込みIncluding Sub-Views

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'])

指定した論理条件にもとづいて@includeしたい場合は、@includeWhenディレクティブを使用します。If you would like to @include a view depending on a given boolean condition, you may use the @includeWhen directive:

@includeWhen($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 sub-directory, 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 environment. We may do this in the boot method of our AppServiceProvider:

use Illuminate\Support\Facades\Blade;

/**
 * 全アプリケーションサービスの初期起動
 *
 * @return void
 */
public function boot()
{
    Blade::if('env', function ($environment) {
        return app()->environment($environment);
    });
}

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

@env('local')
    // アプリケーションはlocal環境
@elseenv('testing')
    // アプリケーションはtesting環境
@else
    // アプリケーションは、local環境でもtesting環境でもない
@endenv

章選択

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作