基本的な使用法Basic Usage
ビューはアプリケーションとして動作するHTMLにより構成されており、コントローラー/アプリケーションロジックをプレゼンテーションロジックから分離します。ビューはresources/views
ディレクトリに保存します。Views contain the HTML served by
your application and separate your controller /
application logic from your presentation logic.
Views are stored in the resources/views
directory.
シンプルなビューは、以下のような形態です。A simple view might look something like this:
<!-- resources/views/greeting.phpとして保存されているビュー -->
<html>
<body>
<h1>Hello, <?php echo $name; ?></h1>
</body>
</html>
このビューをresources/views/greeting.php
として保存していますので、以下のようにグローバルview
ヘルパ関数を使用し結果を返します。Since this view is stored at
resources/views/greeting.php
, we may
return it using the global view
helper
function like so:
Route::get('/', function () {
return view('greeting', ['name' => 'James']);
});
ご覧の通り、view
ヘルパに渡している最初の引数は、resources/views
ディレクトリー中のビューファイル名に対応しています。2つ目の引数は、ビューで使用するデータの配列です。上記の例では、ビューにname
変数を渡し、echo
で表示しているだけです。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. In this case,
we are passing the name
variable, which
is displayed in the view by executing
echo
on the variable.
もちろん、ビューはresources/views
ディレクトリのサブディレクトリにネストすることもできます。ネストしたビューを参照するために「ドット」記法が使えます。例えば、ビューがresources/views/admin/profile.php
として保存するなら、次のように指定します。Of course, views may also be
nested within sub-directories 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.php
, you
may reference it like so:
return view('admin.profile', $data);
ビューの存在を検査Determining If A View Exists
ビューが存在しているかを判定する必要があれば、view
ヘルパを引数無しで呼び出した後に続けて、exists
メソッドを使用します。このメソッドはビューが存在している場合にtrue
を返します。If you need to determine if a
view exists, you may use the exists
method after calling the view
helper
with no arguments. This method will return
true
if the view exists on
disk:
if (view()->exists('emails.customer')) {
//
}
view
ヘルパが引数無しで呼び出されると、Illuminate\Contracts\View\Factory
のインスタンスが返されますので、ファクトリのメソッドが利用できます。When the view
helper
is called without arguments, an instance of
Illuminate\Contracts\View\Factory
is
returned, giving you access to any of the factory's
methods.
ビューデータView Data
ビューにデータを渡すPassing Data To Views
前例で見たように、簡単にデータをビューに渡せます。As you saw in the previous examples, you may easily pass an array of data to views:
return view('greetings', ['name' => 'Victoria']);
この方法で情報を渡す場合、$data
はキー/値ペアの配列です。ビューの中で各値へは対抗するキーでアクセスできます。たとえば<?php
echo $key;
?>
のように表示可能です。全データをview
ヘルパ関数に渡す代わりに、with
メソッドでビューに渡すデータを個別に追加することもできます。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 its corresponding key, such
as <?php echo $key; ?>
. 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:
return view('greeting')->with('name', 'Victoria');
全ビュー間のデータ共有Sharing Data With All Views
アプリケーションでレンダーする全ビューに対し、一部のデータを共有する必要があることも多いと思います。ビューファクトリのshare
メソッドで行えます。通常、サービスプロバイダのboot
メソッド内でshare
を呼び出します。AppServiceProvider
に追加しても良いですし、独立したサービスプロバイダを作成することもできます。Occasionally, you may need to
share a piece of data with all views that are
rendered by your application. You may do so using
the view factory's share
method.
Typically, you should place calls to
share
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:
<?php
namespace App\Providers;
class AppServiceProvider extends ServiceProvider
{
/**
* アプリケーションサービスの初期処理
*
* @return void
*/
public function boot()
{
view()->share('key', 'value');
}
/**
* サービスプロバイダー登録
*
* @return void
*/
public function register()
{
//
}
}
ビューコンポーザ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 can help you organize that logic into a single location.
サービスプロバイダの中にビューコンポーザを組み込みましょう。View
ファサードの裏で動作しているIlluminate\Contracts\View\Factory
契約の実装にアクセスします。Laravelはデフォルトのビューコンポーザ置き場を用意していないことに注意してください。お好きな場所に置くことができます。たとえば、App\Http\ViewComposers
ディレクトリを作成することもできます。Let's register our view composers
within a service
provider[/docs/{{version}}/providers]. We'll
use the view
helper to access the
underlying
Illuminate\Contracts\View\Factory
contract implementation. Remember, Laravel does not
include a default directory for view composers. You
are free to organize them however you wish. For
example, you could create an
App\Http\ViewComposers
directory:
<?php
namespace App\Providers;
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()
{
//
}
}
新しいサービスプロバイダをビューコンポーザ登録のために作成したら、config/app.php
設定ファイルのproviders
配列へ追加する必要があるのを忘れないでください。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
ビューがレンダーされるたび実行される、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\View\View;
use App\Repositories\UserRepository;
class ProfileComposer
{
/**
* userリポジトリの実装
*
* @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());
}
}
ビューがレンダーされる直前に、Illuminate\View\View
インスタンスに対しコンポーザのcompose
メソッドが呼びだされます。Just before the view is rendered,
the composer's compose
method is called
with the Illuminate\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.
複数ビューへの適用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:
view()->composer(
['profile', 'dashboard'],
'App\Http\ViewComposers\MyViewComposer'
);
全ビューコンポーザに適用できるように、composer
メソッドでは*
をワイルドカードとして使用できます。The composer
method
accepts the *
character as a wildcard,
allowing you to attach a composer to all
views:
view()->composer('*', function ($view) {
//
});
ViewクリエーターView Creators
ビュークリエイターは、ビューコンポーザとほぼ同じ働きをします。しかし、ビューがレンダーされるまで待つのではなく、インスタンス化されるとすぐに実行されます。ビュークリエイターを登録するには、creator
メソッドを使います。View creators
are very similar to view composers; however, they
are fired immediately when the view is instantiated
instead of waiting until the view is about to
render. To register a view creator, use the
creator
method:
view()->creator('profile', 'App\Http\ViewCreators\ProfileCreator');