PHPの基礎 - テンプレート方式

提供: MochiuWiki : SUSE, EC, PCB

2024年11月8日 (金) 17:06時点におけるWiki (トーク | 投稿記録)による版 (テンプレートエンジンの使用)

概要

テンプレート方式とは、HTMLのデザイン部分とPHPのロジック部分を分離することである。
これにより、デザイナと開発者が別々に作業しやすくなり、コードの保守性も向上する。

テンプレート方式を採用する主なメリットを以下に示す。

  • コードの可読性向上
  • メンテナンス性の向上
  • チーム開発での作業効率向上
  • デザインの一貫性維持が容易


代表的なテンプレートの実装方法を以下に示す。

  • 基本的な分離方式
    PHPファイルとHTMLファイルを分けて、includeで結合する。
  • テンプレートエンジンの使用
    Smarty、Twig等のテンプレートエンジンを使用する。


なお、テンプレート方式を導入する場合は、プロジェクトの規模や要件に応じて適切な方法を選択することが重要である。
小規模なプロジェクトの場合は基本的な分離方式で十分の可能性があり、大規模なプロジェクトではテンプレートエンジンの採用を検討する。


基本的な分離方式

PHPファイルとHTMLファイルを分けて、include文で結合する方法である。

 // index.php
 
 <?php
    $title   = "Webサイトのタイトル";
    $content = "ここに本文を入力する";
 
    include 'template.html';
 ?>


 <!-- template.html -->
 
 <!DOCTYPE html>
 <html>
 <head>
    <!-- 変数titleを使用する -->
    <title><?php echo $title; ?></title>
 </head>
 <body>
    <!-- 変数contentを使用する -->
    <?php echo $content; ?>
 </body>
 </html>



レイアウトの共通化

ヘッダ部やフッタ部では、共通部分を別ファイルとして管理することにより、保守性が向上する。

 // header.php
 
 <!DOCTYPE html>
 <html>
 <head>
    <title><?php echo $title; ?></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/css/style.css">
 </head>
 <body>
    <header>
       <nav>
          <ul>
             <li><a href="/">ホーム</a></li>
             <li><a href="/about">会社概要</a></li>
             <li><a href="/contact">お問い合わせ</a></li>
          </ul>
       </nav>
    </header>


 // footer.php
 
    <footer>
       <div class="footer-content">
          <p>&copy; 2024 会社名 All Rights Reserved.</p>
       </div>
    </footer>
    <script src="/js/main.js"></script>
 </body>
 </html>


 // content.php (このファイルをトップページとする)
 
 <?php
   $title = "ページタイトル";
 
   include 'header.php';
 ?>
 
 <!-- メインコンテンツ -->
 <main>
 <div class="content">
    <h1>ようこそ</h1>
    <p>これはメインコンテンツです。</p>
 </div>
 </main>
 
 <?php
    include 'footer.php';
 ?>



テンプレートエンジンの使用

Smarty、Twig等のテンプレートエンジンを使用する方法がある。 これらは独自の構文を持ち、より柔軟なテンプレート制御が可能である。

  • Twigを使用する場合
 // index.php
 
 <?php
 require_once 'vendor/autoload.php';
 
 $loader = new \Twig\Loader\FilesystemLoader('templates');
 $twig = new \Twig\Environment($loader);
 
 echo $twig->render('template.twig', [
    'title'   => 'Webサイトのタイトル',
    'content' => 'ここに本文が入力する'
 ]);


 {# template.twig #}
 
 <!DOCTYPE html>
 <html>
 <head>
    <title>{{ title }}</title>
 </head>
 <body>
    {{ content }}
 </body>
 </html>