LoginSignup
12
13

More than 5 years have passed since last update.

共通のテンプレートを切り出す方法

Last updated at Posted at 2014-09-07

htmlの共通ヘッダーとかページ全体のレイアウトをいちいち全てのviewに同じものを書くのは無駄なので別ファイルに切り出す方法。ちなみにテンプレートエンジン使えば簡単にできると思うが今回はControllerだけで解決する。公式はこちら

  1. 共通のviewを作る
  2. \Fuel\Core\Contoller_Templateを継承する
  3. Controllerでアサインする

1. 共通のviewを作る

デフォルトでは fuel/app/views/ 以下に template.php という名前で配置する。

fuel/app/views/template.php
<!DDCTYPE>
<html>
  <head>
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <?php echo $content; ?>
  </body>
</html>

2. \Fuel\Core\Contoller_Templateを継承する

既存で \Fuel\Core\Contoller を継承してるControllerとかあったら \Fuel\Core\Contoller_Temaplte に変更すればそのまま使える。

fuel/app/classes/controller/app.php
<?php

class Controller_App extends Controller_Template
{
}

3. Controllerでアサインする

共通のviewで描画しようとしてる変数に値をアサインする。今回の例だと $title$content に値を挿入する。

fuel/app/classes/controller/app.php
<?php

class Controller_App extends Controller_Template
{
    public function action_index()
    {
        $this->template->title = 'タイトル';
        $this->template->content = View::forge('hoge/fuga');
    }
}

Tips

デフォルトの共通view名を変更したい

fuel/core/classes/controller/template.php$template を変更すればok

<?php

namespace Fuel\Core;

abstract class Controller_Template extends \Controller
{
    /**
    * @var string page template
    */
    public $template = 'template';  //これ

/// 略 ///
}

ページ毎に共通viewを変更したい

例えば管理者用ページとその他のページのレイアウトを変えたいとか。レイアウトを変えたいControllerで$template変数をオーバーライドすればok

fuel/app/classes/controller/admin.php
<?php

class Controller_Admin extends Controller_Template
{

    $template = 'template_admin';  //管理者用レイアウト

    public function action_index()
    {
        $this->template->title = 'タイトル';
        $this->template->content = View::forge('hoge/fuga');
    }
}
12
13
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
12
13