「PHPの基礎 - テンプレート方式」の版間の差分

118行目: 118行目:


== テンプレートエンジンの使用 ==
== テンプレートエンジンの使用 ==
Smarty、Twig等のテンプレートエンジンを使用する方法がある。
Smarty、Twig等のテンプレートエンジンを使用する方法がある。<br>
これらは独自の構文を持ち、より柔軟なテンプレート制御が可能である。<br>
これらは独自の構文を持ち、より柔軟なテンプレート制御が可能である。<br>
<br>
<br>
* Twigを使用する場合
==== Twigを使用する場合 ====
  <syntaxhighlight lang="php">
  <syntaxhighlight lang="php">
  // index.php
  // index.php
149行目: 149行目:
  </body>
  </body>
  </html>
  </html>
</syntaxhighlight>
<br>
==== Laravelを使用する場合 ====
LaravelのBladeテンプレートエンジンは、PHPの機能を損なうことなく、保守性の高いテンプレートを作成できる機能を提供している。<br>
<br>
Bladeテンプレートの特徴を以下に示す。<br>
* @extends、@section、@yield によるレイアウトの継承
* {{ }} による変数の出力 (自動エスケープ付き)
* {!! !!} によるHTMLエスケープなしの出力
* @if、@foreach等のディレクティブ
* コンポーネントによる再利用可能なUI部品の作成
* バリデーションエラーの表示が簡単
* @auth、@guest等の認証関連ディレクティブ
<br>
* Bladeの基本的な構造
<syntaxhighlight lang="php">
// routes/web.php
Route::get('/', function () {
    return view('welcome', [
      'title'  => 'Webサイトのタイトル',
      'content' => 'ここに本文を入れる'
    ]);
});
</syntaxhighlight>
<br>
<syntaxhighlight lang="php">
// resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>@yield('title')</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    @vite([
      'resources/css/app.css',
      'resources/js/app.js'
    ])
</head>
<body>
    <header>
      @include('layouts.navigation')
    </header>
    <main>
      @yield('content')
    </main>
    <footer>
      @include('layouts.footer')
    </footer>
</body>
</html>
</syntaxhighlight>
<br>
<syntaxhighlight lang="php">
// resources/views/welcome.blade.php
@extends('layouts.app')
@section('title', $title)
@section('content')
    <div class="container">
      <h1>{{ $title }}</h1>
      <p>{{ $content }}</p>
      {{-- 条件分岐の例 --}}
      @if (Auth::check())
          <p>ようこそ、{{ Auth::user()->name }}さん</p>
      @else
          <p>ログインしてください</p>
      @endif
      {{-- ループの例 --}}
      @foreach ($items as $item)
          <div class="item">
            {{-- エスケープなしで出力する場合 --}}
            {!! $item->description !!}
          </div>
      @endforeach
    </div>
@endsection
</syntaxhighlight>
<br>
* コンポーネントの使用例
<syntaxhighlight lang="php">
// resources/views/components/button.blade.php
<button {{ $attributes->merge(['class' => 'btn']) }}>
    {{ $slot }}
</button>
</syntaxhighlight>
<br>
<syntaxhighlight lang="php">
// resources/views/welcome.blade.php での使用例
<x-button class="btn-primary">
    クリックしてください
</x-button>
</syntaxhighlight>
<br>
* 共通パーツの分離例
<syntaxhighlight lang="php">
// resources/views/layouts/navigation.blade.php
<nav>
    <ul>
      <li><a href="{{ route('home') }}">ホーム</a></li>
      <li><a href="{{ route('about') }}">会社概要</a></li>
      <li><a href="{{ route('contact') }}">お問い合わせ</a></li>
    </ul>
</nav>
  </syntaxhighlight>
  </syntaxhighlight>
<br><br>
<br><br>