基本的な使用法Basic Usage
ビューはアプリケーションで動くHTMLにより構成されており、コントローラーとドメインロジックをプレゼンテーションロジックから分離するための便利な手法として役立ちます。ビューはresources/viewsディレクトリーに保存します。Views contain the HTML served by your application, and serve as a convenient method of separating your controller and domain logic from your presentation logic. Views are stored in the resources/views directory.
シンプルなビューは、以下のような形態です。A simple view looks like this:
<!-- resources/views/greeting.phpとして保存されているビュー -->
<html>
<body>
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
ビューは次のように、ブラウザーへ送り返します。The view may be returned to the browser like so:
Route::get('/', function()
{
return view('greeting', ['name' => 'James']);
});
ご覧の通り、viewヘルパに渡している最初の引数は、resources/viewsディレクトリー中のビューファイル名に対応しています。2つ目の引数は、ビューで使用するデータの配列です。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 passed to helper is an array of data that should be made available to the view.
もちろん、ビューはresources/viewsディレクトリーのサブディレクトリーにネストすることもできます。例えば、ビューがresources/views/admin/profile.phpに保存されていれば、次のように指定します。Of course, views may also be nested within sub-directories of the resources/views directory. For example, if your view is stored at resources/views/admin/profile.php, it should be returned like so:
return view('admin.profile', $data);
ビューのデータ受け取りPassing Data To Views
// 便利なアプローチを使用する
$view = view('greeting')->with('name', 'Victoria');
// マジックメソッドを利用する
$view = view('greeting')->withName('Victoria');
上の例の場合、ビューの中から$name変数へアクセスでき、値Victoriaを取得できます。In the example above, the variable $name is made accessible to the view and contains Victoria.
お好みならば、viewヘルパの第2引数にデーターの配列を渡すこともできます。If you wish, you may pass an array of data as the second parameter to the view helper:
$view = view('greetings', $data);
この方法で情報を渡す場合、$dataはキー/値ペアの配列です。ビューの中で各値へは対抗するキーでアクセスできます。$data['key']が存在する場合、{{ $key }}のようにです。When passing information in this manner, $data should be an array with key/value pairs. Inside your view, you can then access each value using it's corresponding key, like {{ $key }} (assuming $data['key'] exists).
全ビューとのデータ共有Sharing Data With All Views
たまにアプリケーションの全ビューで表示される一部のデータを共有したい場合もあるでしょう。いくつかの選択肢があり、viewヘルパかIlluminate\Contracts\View\Factory契約、ワイルドカードビューコンポーサーです。Occasionally, you may need to share a piece of data with all views that are rendered by your application. You have several options: the view helper, the Illuminate\Contracts\View\Factory contract[/docs/{{version}}/contracts], or a wildcard view composer[#view-composers].
viewヘルパを使用する例です。For example, using the view helper:
view()->share('data', [1, 2, 3]);
Viewファサードを使用することもできます。You may also use the View facade:
View::share('data', [1, 2, 3]);
通常、サービスプロバイダーのbootメソッドの中で、shareメソッドを呼び出します。自由にAppServiceProviderへ付け足すか、専用のサービスプロバイダーを生成してコードを書きましょう。Typically, you would place calls to the share method within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.
注目:
viewヘルパを引数なしで呼び出すと、Illuminate\Contracts\View\Factory契約の実装が返されます。Note: When theviewhelper is called without arguments, it returns an implementation of theIlluminate\Contracts\View\Factorycontract.
ビューの存在判定Determining If A View Exists
ビューが存在しているかを判定する必要があるなら、existsメソッドを使用します。If you need to determine if a view exists, you may use the exists method:
if (view()->exists('emails.customer'))
{
//
}
ファイルパス指定によるビュー生成Returning A View From A File Path
ご希望なら、絶対ファイルパスを指定し、ビューを生成することもできます。If you wish, you may generate a view from a fully-qualified file path:
return view()->file($pathToFile, $data);
ビューコンポーサーView Composers
ビューコンポーサーは、ビューがレンダーされる時に呼び出される、コールバックかクラスメソッドのことです。もし、ビューがレンダーされるたびに、結合したい情報があるなら、ビューコンポーサーがロジックを一箇所にまとめるのに役立ちます。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 organizes that logic into a single location.
ビューコンポーサーの定義Defining A View Composer
サービスプロバイダーの中にビューコンポーサーを組み込みましょう。Viewファサードで動作しているIlluminate\Contracts\View\Factory契約の実装にアクセスします。Let's organize our view composers within a service provider[/docs/{{version}}/providers]. We'll use the View facade to access the underlying Illuminate\Contracts\View\Factory contract implementation:
<?php namespace App\Providers;
use View;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider {
/**
* コンテナに結合を登録する
*
* @return void
*/
public function boot()
{
// クラスによるコンポーサーの使用…
View::composer('profile', 'App\Http\ViewComposers\ProfileComposer');
// クロージャーによるコンポーサーの使用
View::composer('dashboard', function($view)
{
});
}
/**
* サービスプロバイダーの登録
*
* @return void
*/
public function register()
{
//
}
}
注意: Laravelはビューコンポーサー用のディレクトリーをデフォルトで用意していません。お好きな場所に作成してください。例えば、
App\Http\ViewComposersディレクトリーを作成できます。Note: Laravel does not include a default directory for view composers. You are free to organize them however you wish. For example, you could create anApp\Http\ViewComposersdirectory.
config/app.php設定ファイルの中のproviders配列にサービスプロバイダーを追加するのを忘れないでください。Remember, you will need to add the service provider to the providers array in the config/app.php configuration file.
では、profileビューがレンダーされるたび実行される、ProfileComposer@composeメソッドをコンポーサーとして登録してみましょう。まず、このコンポーサークラスを定義します。Now that we have registered the composer, the ProfileComposer@compose method will be executed each time the profile view is being rendered. So, let's define the composer class:
<?php namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
use Illuminate\Users\Repository as UserRepository;
class ProfileComposer {
/**
* ユーザーリポジトリーの実装
*
* @var UserRepository
*/
protected $users;
/**
* 新しいプロファイルコンポーサーの生成
*
* @param UserRepository $users
* @return void
*/
public function __construct(UserRepository $users)
{
// サービスコンテナにより、自動的に依存が解決される
$this->users = $users;
}
/**
* ビューへデーターを結合する
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('count', $this->users->count());
}
}
ビューがレンダーされる直前に、コンポーサーのcomposeメソッドがIlluminate\Contracts\View\Viewインスタンスで呼び出されます。ビューにデーターを結合するために、withメソッドを使うこともできます。Just before the view is rendered, the composer's compose method is called with the Illuminate\Contracts\View\View instance. You may use the with method to bind data to the view.
注目: すべてのビューコンポーサーはサービスコンテナにより依存解決されます。ですから、コンポーサーのコンストラクターに必要な依存をタイプヒントで指定できます。Note: 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.
ワイルドカードビューコンポーサーWildcard View Composers
composerメソッドは、*文字をワイルドカードとして扱います。そのため、次のように全ビューにコンポーサーを指定できます。The composer method accepts the * character as a wildcard, so you may attach a composer to all views like so:
View::composer('*', function($view)
{
//
});
複数ビューへの適用Attaching A Composer To Multiple Views
また、複数のビューに対し、一度にビューコンポーサーを指定することもできます。You may also attach a view composer to multiple views at once:
View::composer(['profile', 'dashboard'], 'App\Http\ViewComposers\MyViewComposer');
複数のコンポーサー定義Defining Multiple Composers
一度にコンポーサーのグループを登録するためには、composersメソッドが使えます。You may use the composers method to register a group of composers at the same time:
View::composers([
'App\Http\ViewComposers\AdminComposer' => ['admin.index', 'admin.profile'],
'App\Http\ViewComposers\UserComposer' => 'user',
'App\Http\ViewComposers\ProductComposer' => 'product'
]);
ビュークリエイターView Creators
ビュークリエイターは、ビューコンポーサーとほとんど同じ働きをします。しかしこれは、ビューがインスタンス化されるとすぐに実行されます。ビュークリエイターを登録するには、creatorメソッドを使います。View creators work almost exactly like view composers; however, they are fired immediately when the view is instantiated. To register a view creator, use the creator method:
View::creator('profile', 'App\Http\ViewCreators\ProfileCreator');