イントロダクションIntroduction
もちろん、ルートやコントローラから直接HTML文書全体の文字列を返すのは現実的ではありません。ありがたいことに、ビューがすべてのHTMLを別々のファイルに格納する便利な方法を提供します。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.
ビューは、コントローラ/アプリケーションロジックをプレゼンテーションロジックから分離し、resources/views
ディレクトリに格納されます。Laravelを使用する場合、ビューテンプレートは通常、Bladeテンプレート言語で記述します。単純なビューは以下のようになります。Views separate your controller /
application logic from your presentation logic and
are stored in the resources/views
directory. When using Laravel, view templates are
usually written using the Blade templating
language[/docs/{{version}}/blade]. 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']);
});
Bladeドキュメントを確認してください。[!NOTE]
Note: Bladeテンプレートの作成方法の詳細をお探しですか?最初に完全な
Looking for more information on how to write Blade templates? Check out the full Blade documentation[/docs/{{version}}/blade] to get started.
React/Vueでのビュー記述Writing Views in React / Vue
フロントエンドのテンプレートをBladeを使ってPHPで書く代わりに、多くの開発者はReactやVueを使ってテンプレートを書くことを好むようになりました。Laravelでは、Inertiaというライブラリのおかげで、React / VueのフロントエンドをLaravelのバックエンドに簡単に結びつけることができ、典型的なSPAの構築のように複雑なことは必要ありません。Instead of writing their frontend templates in PHP via Blade, many developers have begun to prefer to write their templates using React or Vue. Laravel makes this painless thanks to Inertia[https://inertiajs.com/], a library that makes it a cinch to tie your React / Vue frontend to your Laravel backend without the typical complexities of building an SPA.
BreezeとJetstreamのスターターキットは、Inertiaを利用する次のLaravelアプリケーションのための素晴らしい開始点を提供します。また、Laravel Bootcampは、VueとReactの例を含め、Inertiaを利用したLaravelアプリケーションの構築の完全なデモンストレーションを提供しています。Our Breeze and Jetstream starter kits[/docs/{{version}}/starter-kits] give you a great starting point for your next Laravel application powered by Inertia. In addition, the Laravel Bootcamp[https://bootcamp.laravel.com] provides a full demonstration of building a Laravel application powered by Inertia, including examples in Vue and React.
ビューの作成とレンダCreating and Rendering Views
アプリケーションのresources/views
ディレクトリに.blade.php
拡張子のファイルを置くか、make:view
Artisan コマンドを使用してビューを作成できます。You
may create a view by placing a file with the
.blade.php
extension in your
application's resources/views
directory
or by using the make:view
Artisan
command:
php artisan make:view greeting
.blade.php
拡張子は、そのファイルがBlade
テンプレートを含んでいることをフレームワークに知らせます。BladeテンプレートにはHTMLとBladeディレクティブが含まれており、簡単に値をエコーしたり、"if"ステートメントを作成したり、データを反復処理したりできます。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);
Warning! ビューのディレクトリ名には、
.
文字を含めてはいけません。[!WARNING]
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('admin.profile')) {
// ...
}
ビューにデータを渡す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
{
/**
* 全アプリケーションサービスの登録
*/
public function register(): void
{
// ...
}
/**
* 全アプリケーションサービスの初期起動
*/
public function boot(): void
{
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.
通常、ビューコンポーザはアプリケーションのサービスプロバイダの1つで登録します。この例では、App\Providers\AppServiceProvider
へこのロジックを格納すると仮定しましょう。Typically, view composers will be
registered within one of your application's
service
providers[/docs/{{version}}/providers]. In
this example, we'll assume that the
App\Providers\AppServiceProvider
will
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;
use Illuminate\Support\ServiceProvider;
use Illuminate\View\View;
class AppServiceProvider extends ServiceProvider
{
/**
* 全アプリケーションサービスの登録
*/
public function register(): void
{
// ...
}
/**
* 全アプリケーションサービスの初期起動
*/
public function boot(): void
{
// クラスベースのコンポーザを使用する
Facades\View::composer('profile', ProfileComposer::class);
// クロージャベースのコンポーザを使用
Facades\View::composer('welcome', function (View $view) {
// ...
});
Facades\View::composer('dashboard', function (View $view) {
// ...
});
}
}
コンポーザを登録したので、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
{
/**
* 新しいプロフィールコンポーザの生成
*/
public function __construct(
protected UserRepository $users,
) {}
/**
* データをビューと結合
*/
public function compose(View $view): void
{
$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;
use Illuminate\Support\Facades\View;
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:
use Illuminate\Support\Facades;
use Illuminate\View\View;
Facades\View::composer('*', function (View $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