LoginSignup
43

More than 5 years have passed since last update.

viewの共通テンプレートを作成する

Posted at

viewの共通テンプレートを作成する

目的:ヘッダー、フッターを流用し、コンテンツだけアクション毎に変えたい

手順

1. テンプレート(template.php)を作成する

\fuelphp\fuel\app\views\template.php
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <header>
        <!-- header.phpファイルを読み込む-->
        <?php echo $header; ?>
    </header>
    <div id="content">
        <!-- 各アクションの内容を読み込む-->
        <?php echo $content; ?>
    </div>
    <footer>
        <!-- footer.phpファイルを読み込む-->
        <?php echo $footer; ?>
    </footer>
</body>
</html>

2. 読み込ませるheader.php, footer.phpを作成する
HEADER=ここはheaderの領域です
FOOTER=ここはfooterの領域です と定数で設定

\fuel\app\views\parts\header.php
<div>
    <?php echo HEADER; ?>
</div>
\fuel\app\views\parts\footer.php
<div>
    <?php echo FOOTER; ?>
</div>

3. Controller_Templateを継承したController_Base(base.php)を作成する
今後、ここで共通なものを一箇所にまとめる

\fuel\app\classes\controller\base.php
class Controller_Base extends Controller_Template
{
    public function before()
    {
        parent::before();
        //header.phpをテンプレートの$headerとbindさせる。
        $this->template->header = View::forge('parts/header');
        //footer.phpをテンプレートの$footerとbindさせる。
        $this->template->footer = View::forge('parts/footer');
    }

    public function after($response)
    {
        $response = parent::after($response); // あなた自身のレスポンスオブジェクトを作成する場合は必要ありません。
        return $response; // after() は確実に Response オブジェクトを返すように
    }
}

4. Controller_Baseを継承したController_Hello(hello.php)を作成し、
indexアクションを実装する

\fuel\app\classes\controller\hello.php
class Controller_Hello extends Controller_Base
{
    public function action_index()
    {
        //template.phpのcontentとアクション毎のviewをbindさせる
        $this->template->content = View::forge('hello/index');
        //デフォルト設定を変えず、template.phpのファイル名を変更しない場合はtemplateのviewオブジェクトを返す
    }
}

5. viewファイルindex.phpを作成する

\fuel\app\views\hello\index.php
<div>
    コンテンツ領域です
</div>

6. 結果

result
<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <header>
        <!-- header.phpファイルを読み込む-->
        <div>
        ここはheaderの領域です
     </div>
    </header>
    <div id="content">
        <!-- 各アクションの内容を読み込む-->
      <div>
          コンテンツ領域です
    </div>
    </div>
    <footer>
        <!-- footer.phpファイルを読み込む-->
        <div>
          ここはfooterの領域です
    </div>
    </footer>
</body>
</html>

公式サイト
Template コントローラ
view

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
43