LoginSignup
0
0

More than 1 year has passed since last update.

Chapter3 ビューとテンプレート(3-1〜3-3)

Last updated at Posted at 2022-06-14

3-1 PHPテンプレートの利用

テンプレートの利用

index.php
<html>
    <head>
        <title>Hello/Index</title>
        <style>
          body {
            font-size: 16pt;
            color: #999;
          }
          h1 {
            font-size: 120pt;
            text-align: right;
            color: #fafafa;
            margin: -50px 0px -120px 0px;
          }
        </style>
    </head>
    <body>
        <h1>Hello</h1>
        <p>This is a sample page with php-template.</p>
    </body>
</html>

web.php
Route::get('hello', function() {
  return view('hello.index');
});

Viewメソッド

view('フォルダ名 . ファイル名')

コントローラでテンプレートを使う

web.php
Route::get('hello','App\Http\Controllers\HelloController@index');
HelloController.php
class HelloController extends Controller
{
    public function index() {

        return view('hello.index');

    }
}

コントローラーから変数を渡され、画面表示する

HelloController.php
class HelloController extends Controller
{
    public function index() {

        $data = ['msg'=>'これはコントローラから渡されたメッセージです。'];
        return view('hello.index', $data);

    }
}

コントローラーからルートパラメータを渡され、画面表示する

web.php
Route::get('hello/{id?}','App\Http\Controllers\HelloController@index');
HelloController.php
class HelloController extends Controller
{
    public function index($id='zero') {

        $data = [
            'msg'=>'これはコントローラから渡されたメッセージです。',
            'id'=>$id
        ];
        return view('hello.index', $data);

    }
}

Requestインスタンスにクエリ文字列を渡たし、画面表示する

web.php
Route::get('hello','App\Http\Controllers\HelloController@index');
HelloController.php
class HelloController extends Controller
{
    public function index(Request $request) {

        $data = [
            'msg'=>'これはコントローラから渡されたメッセージです。',
            'id'=>$request->id
        ];
        return view('hello.index', $data);

    }
}

http://127.0.0.1:8000/hello?id=worldのアドレスにアクセスすると、
Requestインスタンスのidに「world」というクエリ文字列を渡し、
連想配列$dataのidに「world」用意した状態で、
テンプレートindex.phpに渡す。

3-2 Bladeテンプレートを使う

Bladeテンプレートを作成する

HelloController.php
class HelloController extends Controller
{
    public function index(Request $request) {

        $data = [
            'msg'=>'これはBladeを利用したメッセージです。'
        ];
        return view('hello.index', $data);

    }
}
index.blade.php
<html>
<head>
    <title>Hello/Index</title>
    <style>
        body {
            font-size: 16pt;
            color: #999;
        }
        h1 {
            font-size: 50pt;
            text-align: right;
            color: #f6f6f6;
            margin: -20px 0px -30px 0px;
        }
    </style>
</head>
<body>
<h1>Blade/Index</h1>
<p>{{$msg}}</p>
</body>
</html>

フォームを利用する

web.php
Route::get('hello','App\Http\Controllers\HelloController@index');
Route::post('hello','App\Http\Controllers\HelloController@post');
HelloController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\Response;

class HelloController extends Controller
{
    public function index() {

        $data = [
            'msg'=>'お名前を入力して下さい。'
        ];
        return view('hello.index', $data);

    }

    public function post(Request $request) {

        $msg = $request->msg;

        $data = [
          'msg'=>'こんにちは、' . $msg . 'さん!'
        ];
        return view('hello.index', $data);

    }

}
index.blade.php
<html>
<head>
    <title>Hello/Index</title>
    <style>
        body {
            font-size: 16pt;
            color: #999;
        }
        h1 {
            font-size: 50pt;
            text-align: right;
            color: #f6f6f6;
            margin: -20px 0px -30px 0px;
        }
    </style>
</head>
<body>
<h1>Blade/Index</h1>
<p>{{$msg}}</p>
<form method="POST" action="/hello">
    @csrf
    <input type="text" name="msg">
    <input type="submit">
</form>
</body>
</html>

3-3 Bladeの構文

変数などの値を埋め込む時に使用する{{$msg}}{{ }}は、
HTMLエスケープ処理(中に書いた文字列はHTMLタグとして認識されなくなる)されます。
*HTMLエスケープ処理をされて欲しくない場合は、{!! !!}と記述します。

そのため、

sample.php
<p>{{ '<p>ABC</p>' }}</p>
<p>{!! '<p>ABC</p>' !!}</p>

上の場合、HTMLタグとして認識されず、「<p>ABC</p>」と表示され、
下の場合、HTMLタグとして認識されるので、「ABC」と表示されます。

@ifディレクティブ

◆条件がtureの時に表示する
(条件が正しければ、「出力条件A」を表示する)

sample.php
@if ()
    **出力内容A**
@endif

◆条件が異なる表示をする
(条件が正しければ、「出力条件A」を表示し、
 異なる場合は「出力内容B」を表示する)

sample.php
@if ()
    **出力内容A**
    @else
    **出力内容B**
@endif

◆複数の条件を設定する
(条件が正しければ、「出力条件A」を表示し、
 異なる場合は「出力内容B」を表示し、
 さらに異なる場合は「出力内容C」を表示する。)

sample.php
@if ()
    **出力内容A**
    @elseif ()
    **出力内容B**
    @else
    **出力内容C**
@endif

特殊なディレクティブ

◆条件に合わないとき、表示させる。

sample.php
@unless (*条件*)
    **表示内容**
@endunless

◆変数が空のとき、表示させる。

sample.php
@empty (*変数*)
    **表示内容**
@endempty

◆変数が定義済みのとき、表示させる。

sample.php
@isset (*変数*)
    **表示内容**
@endisset

*変数が定義されていて、空(null)でない場合に、表示させます。
(定義されていても、nullの場合表示されない。)
@elseは変数が未定義だった場合に表示されます。

繰り返しのディレクティブ

◆条件に合わなくなるまで繰り返す(for構文)

sample.php
@for ( 初期化 ; 条件; 後処理 )
    **繰り返す表示**
@endfor

◆配列から変数を取り出せなくなるまで繰り返す(foreach構文)

sample.php
@foreach ( $配列 as 変数 )
    **繰り返す表示**
@endforeach

◆配列から変数を取り出せなくなるまで繰り返し、
 空になったら別の処理をさせる(foreach-else構文)

sample.php
@forelse ( $配列 as 変数 )
    **繰り返す表示**
@empty
    **変数が空のとき**
@endforelse

◆条件に合わなくなるまで繰り返す(while構文)

sample.php
@while ( 条件 )
    **繰り返す処理**
@endwhile

*@whileは条件に使っている変数の値が変化しない場合は、
 無限ループとなるため繰り返す処理の中に値を変化させる処理が必要。

繰り返しのディレクティブを利用する

HelloController.php
<?php

class HelloController extends Controller
{
    public function index() {

        $data = ['one','two','three','four','five'];

        return view('hello.index',['data'=>$data]);

    }

}
index.php
<body>
    <h1>Blade/Index</h1>
    <p>&#64;foreachディレクティブの例</p>
    <ol>
        @foreach( $data as $item )
            <li>{{$item}}</li>
        @endforeach
    </ol>
</body>

@break@continue

index.php
<body>
    <h1>Blade/Index</h1>
    <p>&#64;forディレクティブの例</p>
    <ol>
        @for ( $i = 1;$i < 100;$i++ )
            @if ($i % 2 == 1)
                @continue
            @elseif ($i <= 10)
                <li>No,{{$i}}</li>
            @else
                @break
            @endif
        @endfor
    </ol>
</body>

@loopによるルール変数

$loop->index 現在のインデックス(ゼロから)
$loop->iteration現在の繰り返し数(1から開始)
$loop->remaining後何回クリア返すか
$loop->count繰り返しを使っている配列の要素数
$loop->first最初の繰り返しか
$loop->last最後の繰り返しか
$loop->depth繰り返しのネスト数
$loop->parentネストしている場合、親の繰り返しのループ変数を示す

index.php
<body>
    <h1>Blade/Index</h1>
    <p>&#64;forディレクティブの例</p>
    @foreach ( $data as $item )

        @if ($loop->first)
            <p>データ一覧</p>
            <ul>
        @endif
                <li>No,{{$loop->iteration}}. {{$item}}</li>
        @if ($loop->last)
            </ul>
            <p>---ここまで</p>
        @endif

    @endforeach
</body>

@phpディレクティブについて

index.php
<body>
    <h1>Blade/Index</h1>
    <p>&#64;forディレクティブの例</p>
    <ol>
        @php
            $counter =0;
        @endphp
        @while ($counter < count($data))
            <li>{{$data[$counter]}}</li>
            @php
                $counter++;
            @endphp
        @endwhile
    </ol>
</body>

*@phpは便利だが、表示を担当するビューに複雑な処理を記述するのは、
 MVCアーキテクチャの理念からも相反するため、
 @phpを多用する場合はアプローチが適切か再検討する。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0