Readouble

Laravel 8.x ビュー

イントロダクションIntroduction

もちろん、ルートやコントローラから直接HTMLドキュメントの文字列全体を返すことは実用的ではありません。幸い、Laravelのビュー機能はすべてのHTMLを別々のファイルに配置できる便利な方法を提供します。ビューはプレゼンテーションロジックをコントローラ/アプリケーションロジックから分離し、resources/viewsディレクトリ下へ保存します。単純なビューは以下のようになります。Of course, it's not practical to return entire HTML documents strings directly from your routes and controllers. Thankfully, views provide a convenient way to place all of our HTML in separate files. Views separate your controller / application logic from your presentation logic and are stored in the resources/views directory. A simple view might look something like this:

<!-- View stored in resources/views/greeting.blade.php -->

<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

このビューをresources/views/greeting.blade.phpとして保存し、以下のようにグローバルviewヘルパ関数を使用し結果を返します。Since this view is stored at resources/views/greeting.blade.php, we may return it using the global view helper like so:

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

lightbulb">Tip!! Bladeテンプレートの作成方法の詳細をお探しですか?最初に完全なBladeドキュメントを確認してください。{tip} Looking for more information on how to write Blade templates? Check out the full Blade documentation[/docs/{{version}}/blade] to get started.

ビューの作成とレンダーCreating & Rendering Views

アプリケーションのresources/viewsディレクトリに.blade.php拡張子の付いたファイルを配置することで、ビューを作成できます。.blade.php拡張子は、ファイルにBladeテンプレートが含まれていることをフレームワークに通知します。BladeテンプレートはHTML、値を簡単にエコーしたり、"if"文を作成したり、データを反復処理したりできるBladeディレクティブを含みます。You may create a view by placing a file with the .blade.php extension in your application's resources/views directory. The .blade.php extension informs the framework that the file contains a Blade template[/docs/{{version}}/blade]. Blade templates contain HTML as well as Blade directives that allow you to easily echo values, create "if" statements, iterate over data, and more.

ビューを作成したら、グローバルなviewヘルパを使用して、アプリケーションのルートまたはコントローラからビューを返すことができます。Once you have created a view, you may return it from one of your application's routes or controllers using the global view helper:

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

ビューは、Viewファサードを使用して返すこともできます。Views may also be returned using the View facade:

use Illuminate\Support\Facades\View;

return View::make('greeting', ['name' => 'James']);

ご覧のとおり、viewヘルパに渡たす最初の引数は、resources/viewsディレクトリ内のビューファイルの名前に対応しています。2番目の引数は、ビューで使用するデータの配列です。この場合、Blade構文を使用してビューに表示する、name変数を渡しています。As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory. The second argument is an array of data that should be made available to the view. In this case, we are passing the name variable, which is displayed in the view using Blade syntax[/docs/{{version}}/blade].

ネストしたビューディレクトリNested View Directories

ビューは、resources/viewsディレクトリのサブディレクトリ内にネストすることもできます。「ドット」表記は、ネストしたビューを参照するために使用できます。たとえば、ビューがresources/views/admin/profile.blade.phpに保存されている場合、以下のようにアプリケーションのルート/コントローラからビューを返すことができます。Views may also be nested within subdirectories of the resources/views directory. "Dot" notation may be used to reference nested views. For example, if your view is stored at resources/views/admin/profile.blade.php, you may return it from one of your application's routes / controllers like so:

return view('admin.profile', $data);

Note: note ビューのディレクトリ名には、.文字を含めてはいけません。{note} View directory names should not contain the . character.

最初に利用可能なビューCreating The First Available View

Viewファサードのfirstメソッドを使用して、指定したビューの配列に存在する最初のビューを生成できます。これは、アプリケーションまたはパッケージでビューのカスタマイズまたは上書きが許可されている場合に役立つでしょう。Using the View facade's first method, you may create the first view that exists in a given array of views. This may be useful if your application or package allows views to be customized or overwritten:

use Illuminate\Support\Facades\View;

return View::first(['custom.admin', 'admin'], $data);

ビューの存在の判定Determining If A View Exists

ビューが存在しているかを判定する必要があれば、Viewファサードを使います。ビューが存在していれば、existsメソッドはtrueを返します。If you need to determine if a view exists, you may use the View facade. The exists method will return true if the view exists:

use Illuminate\Support\Facades\View;

if (View::exists('emails.customer')) {
    //
}

ビューにデータを渡すPassing Data To Views

前例で見たように、データの配列をビューに渡し、そのデータをビューで使用できます。As you saw in the previous examples, you may pass an array of data to views to make that data available to the view:

return view('greetings', ['name' => 'Victoria']);

この方法で情報を渡す場合、データはキー/値ペアの配列です。ビューにデータを渡した後、<?php echo $name; ?>などのデータキーを使用して、ビュー内の各値にアクセスします。When passing information in this manner, the data should be an array with key / value pairs. After providing data to a view, you can then access each value within your view using the data's keys, such as <?php echo $name; ?>.

データの完全な配列をviewヘルパ関数に渡す代わりに、withメソッドを使用して個々のデータをビューへ追加することもできます。withメソッドはビューオブジェクトのインスタンスを返すため、ビューを返す前にメソッドのチェーンを続けられます。As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view. The with method returns an instance of the view object so that you can continue chaining methods before returning the view:

return view('greeting')
            ->with('name', 'Victoria')
            ->with('occupation', 'Astronaut');

すべてのビューでデータを共有Sharing Data With All Views

時に、アプリケーションがレンダーするすべてのビューとデータを共有する必要が起きます。これは、Viewファサードのshareメソッドで可能です。通常、サービスプロバイダのbootメソッド内でshareメソッドを呼び出す必要があります。それらをApp\Providers\AppServiceProviderクラスへ追加するか、それらを収容するための別のサービスプロバイダを生成することもできます。Occasionally, you may need to share data with all views that are rendered by your application. You may do so using the View facade's share method. Typically, you should place calls to the share method within a service provider's boot method. You are free to add them to the App\Providers\AppServiceProvider class or generate a separate service provider to house them:

<?php

namespace App\Providers;

use Illuminate\Support\Facades\View;

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

    /**
     * 全アプリケーションサービスの初期起動
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
    }
}

ビューコンポーザView Composers

ビューコンポーザは、ビューをレンダーするときに呼び出すコールバックまたはクラスメソッドです。ビューをレンダーするたびにビューへ結合するデータがある場合、ビューコンポーザを使用すると、そのロジックを1つの場所に集約できます。ビューコンポーザは、アプリケーション内の複数のルートかコントローラが同じビューを返し、常に特定のデータが必要な場合にきわめて役立ちます。View composers are callbacks or class methods that are called when a view is rendered. If you have data that you want to be bound to a view each time that view is rendered, a view composer can help you organize that logic into a single location. View composers may prove particularly useful if the same view is returned by multiple routes or controllers within your application and always needs a particular piece of data.

通常、ビューコンポーザーは、アプリケーションのサービスプロバイダのいずれかで登録します。この例では、このロジックを格納するために新しいApp\Providers\ViewServiceProviderを作成したと想定しましょう。Typically, view composers will be registered within one of your application's service providers[/docs/{{version}}/providers]. In this example, we'll assume that we have created a new App\Providers\ViewServiceProvider to house this logic.

Viewファサードのcomposerメソッドを使用して、ビューコンポーザを登録します。Laravelには、クラスベースのビューコンポーザーのデフォルトディレクトリが含まれていないため、自由に整理できます。たとえば、app/View/Composersディレクトリを作成して、アプリケーションのすべてのビューコンポーザを保存できます。We'll use the View facade's composer method to register the view composer. Laravel does not include a default directory for class based view composers, so you are free to organize them however you wish. For example, you could create an app/View/Composers directory to house all of your application's view composers:

<?php

namespace App\Providers;

use App\View\Composers\ProfileComposer;
use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

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

    /**
     * 全アプリケーションサービスの初期起動
     *
     * @return void
     */
    public function boot()
    {
        // クラスベースのコンポーザを使用する
        View::composer('profile', ProfileComposer::class);

        // クロージャベースのコンポーザを使用
        View::composer('dashboard', function ($view) {
            //
        });
    }
}

Note: note 新しいサービスプロバイダをビューコンポーザ登録のために作成した場合は、config/app.php設定ファイルのproviders配列へ追加する必要があるのを忘れないでください。{note} Remember, if you create a new service provider to contain your view composer registrations, you will need to add the service provider to the providers array in the config/app.php configuration file.

コンポーザを登録したので、profileビューがレンダーされるたびにApp\View\Composers\ProfileComposerクラスのcomposeメソッドが実行されます。コンポーザクラスの例を見てみましょう。Now that we have registered the composer, the compose method of the App\View\Composers\ProfileComposer class will be executed each time the profile view is being rendered. Let's take a look at an example of the composer class:

<?php

namespace App\View\Composers;

use App\Repositories\UserRepository;
use Illuminate\View\View;

class ProfileComposer
{
    /**
     * userリポジトリの実装
     *
     * @var UserRepository
     */
    protected $users;

    /**
     * 新しいプロフィールコンポーザの生成
     *
     * @param  \App\Repositories\UserRepository  $users
     * @return void
     */
    public function __construct(UserRepository $users)
    {
        // 依存関係はサービスコンテナによって自動的に解決される
        $this->users = $users;
    }

    /**
     * データをビューと結合
     *
     * @param  \Illuminate\View\View  $view
     * @return void
     */
    public function compose(View $view)
    {
        $view->with('count', $this->users->count());
    }
}

ご覧のとおり、すべてのビューコンポーザはサービスコンテナを介して依存解決されるため、コンポーザのコンストラクタ内で必要な依存関係を依存注入できます。As you can see, all view composers are resolved via the service container[/docs/{{version}}/container], so you may type-hint any dependencies you need within a composer's constructor.

複数ビューへの適用Attaching A Composer To Multiple Views

複数のビューにビューコンポーザを適用するには、composerメソッドの最初の引数にビューの配列を渡してください。You may attach a view composer to multiple views at once by passing an array of views as the first argument to the composer method:

use App\Views\Composers\MultiComposer;

View::composer(
    ['profile', 'dashboard'],
    MultiComposer::class
);

全ビューコンポーザに適用するため、composerメソッドは*をワイルドカードとして使用できます。The composer method also accepts the * character as a wildcard, allowing you to attach a composer to all views:

View::composer('*', function ($view) {
    //
});

ビュークリエータView Creators

ビューの「クリエータ」は、ビューコンポーザと非常によく似ています。ただし、ビューがレンダリングされるまで待つのではなく、ビューがインスタンス化された直後に実行されます。ビュークリエータを登録するには、creatorメソッドを使用します。View "creators" are very similar to view composers; however, they are executed immediately after the view is instantiated instead of waiting until the view is about to render. To register a view creator, use the creator method:

use App\View\Creators\ProfileCreator;
use Illuminate\Support\Facades\View;

View::creator('profile', ProfileCreator::class);

ビューの最適化Optimizing Views

Bladeテンプレートビューはデフォルトでは、オンデマンドでコンパイルされます。ビューをレンダーするリクエストが実行されると、Laravelはコンパイル済みバージョンのビューが存在するかどうかを判断します。ファイルが存在する場合、Laravelはコンパイルされていないビューがコンパイル済みビューよりも最近変更されたかどうかを判断します。コンパイル済みビューが存在しないか、コンパイルされていないビューが変更されている場合、Laravelはビューをコンパイルします。By default, Blade template views are compiled on demand. When a request is executed that renders a view, Laravel will determine if a compiled version of the view exists. If the file exists, Laravel will then determine if the uncompiled view has been modified more recently than the compiled view. If the compiled view either does not exist, or the uncompiled view has been modified, Laravel will recompile the view.

リクエスト中にビューをコンパイルすると、パフォーマンスにわずかな悪影響が及ぶ可能性があるため、Laravelは、アプリケーションで使用するすべてのビューをプリコンパイルするためにview:cache Artisanコマンドを提供しています。パフォーマンスを向上させるために、デプロイプロセスの一部として次のコマンドを実行することを推奨します。Compiling views during the request may have a small negative impact on performance, so Laravel provides the view:cache Artisan command to precompile all of the views utilized by your application. For increased performance, you may wish to run this command as part of your deployment process:

php artisan view:cache

ビューキャッシュを消去するには、view:clearコマンドを使います。You may use the view:clear command to clear the view cache:

php artisan view:clear

章選択

設定

明暗テーマ
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に保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作