Readouble

Laravel 5.1 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. 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/master.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 page, you may use the Blade @extends directive to specify which layout the child page should "inherit". Views which @extends 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.master')

@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.

もちろん生のPHPビューと同様、Bladeビューはグローバルなviewヘルパを使用し、ルートから返すことができます。Of course, just like plain PHP views, Blade views may be returned from routes using the global view helper function:

Route::get('blade', function () {
    return view('child');
});

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

もちろんビューに渡された変数の内容を表示するだけに限られません。PHP関数の結果をechoすることもできます。実際、どんなPHPコードもBladeのecho文の中に書けます。Of course, 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:

現在のUNIXタイムスタンプは {{ time() }}.

注意: Bladeの{{ }}文は自動的にPHPのhtmlentities関数を通し、XSS攻撃を防ぎます。Note: Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks.

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>

こんにちは @{{ 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.

存在時のデータ表示Echoing Data If It Exists

変数をechoしたいが、その変数がセットされているかわからない場合もあるでしょう。複雑なPHPコードを使えば可能です。Sometimes you may wish to echo a variable, but you aren't sure if the variable has been set. We can express this in verbose PHP code like so:

{{ isset($name) ? $name : 'Default' }}

しかし三項演算子の代わりに、Bladeは便利な次の短縮形を提供しています。However, instead of writing a ternary statement, Blade provides you with the following convenient short-cut:

{{ $name or 'Default' }}

この例の場合、$name変数が存在すれば値が表示されます。しかし存在していなければDefaultという言葉が表示されます。In this example, if the $name variable exists, its value will be displayed. However, if it does not exist, the word Default will be displayed.

エスケープしないデータの表示Displaying Unescaped Data

デフォルトでブレードの{{ }}文はXSS攻撃を防ぐために、PHPのhtmlentities関数を自動的に通されます。しかしデータをエスケープしたくない場合は、以下の構文を使ってください。By default, Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax:

Hello, {!! $name !!}.

注意: アプリケーションでユーザーの入力内容をechoする場合は注意が必要です。コンテンツは常に二重の波括弧の記法でHTMLエンティティにエスケープすべきです。Note: Be very careful when echoing content that is supplied by users of your application. Always use the double curly brace syntax to escape any HTML entities in the content.

制御構文Control Structures

テンプレートの継承とデータ表示に付け加え、Bladeは条件文やループなどの一般的なPHPの制御構文の便利な短縮形を提供しています。こうした短縮形はPHP制御構文のきれいで簡潔な記述を提供しつつも、対応するPHPの構文とそっくりです。In addition to template inheritance and displaying data, Blade also provides convenient short-cuts for common PHP control structures, such as conditional statements and loops. These short-cuts 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)
    レコードが一つある!
@elseif (count($records) > 1)
    複数のレコードがある!
@else
    レコードが全くない!
@endif

利便性のため、Bladeでは@unlessディレクティブも提供しています。For convenience, Blade also provides an @unless directive:

@unless (Auth::check())
    ログインしていません。
@endunless

繰り返しLoops

条件文に加え、BladeはPHPがサポートしている繰り返し構文も提供しています。これらも、対応するPHP構文と使い方は一緒です。In addition to conditional statements, Blade provides simple directives for working with PHP's supported 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

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

Bladeの@includeディレクディブを使えば、ビューの中から簡単に他のBladeビューを取り込めます。取り込み元のビューで使用可能な変数は、取り込み先のビューでも利用可能です。Blade's @include directive, allows you to easily include a Blade view from within an existing 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'])

注意: 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 view.

コレクションのレンダービュー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変数としてアクセスしたいと通常は考えるでしょう。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.

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

コメント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中には存在しない --}}

サービス注入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 / interface name of the service you wish to resolve:

@inject('metrics', 'App\Services\MetricsService')

<div>
    月間収入: {{ $metrics->monthlyRevenue() }}.
</div>

Blade拡張Extending Blade

Bladeでは自分のカスタムディレクティブも定義することができます。directiveメソッドを使い、ディレクティブを登録します。Bladeコンパイラーがそのディレクティブを見つけると、引数に指定したコールバックが呼びだされます。Blade even allows you to define your own custom directives. You can use the directive method to register a directive. When the Blade compiler encounters the directive, it calls the provided callback with its parameter.

次の例は@datetime($var)ディレクティブを作成し、渡された$varをフォーマットします。The following example creates a @datetime($var) directive which formats a given $var:

<?php

namespace App\Providers;

use Blade;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * サービス初期処理登録後に実行
     *
     * @return void
     */
    public function boot()
    {
        Blade::directive('datetime', function($expression) {
            return "<?php echo with{$expression}->format('m/d/Y H:i'); ?>";
        });
    }

    /**
     * コンテナ結合の登録
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

ご覧の通り、このディレクティブではLaravelのwithヘルパ関数が使われています。withヘルパはシンプルに指定されたオブジェクト/値を返します。メソッドチェーンを行うのに便利です。このディレクティブにより最終的に生成されるコードは、次の通りです。As you can see, Laravel's with helper function was used in this directive. The with helper simply returns the object / value it is given, allowing for convenient method chaining. The final PHP generated by this directive will be:

<?php echo with($var)->format('m/d/Y H:i'); ?>

章選択

設定

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

ヘッダー項目移動

キーボード操作