LoginSignup
22
26

More than 5 years have passed since last update.

Controller_Templateのaction内で、$this->templateを変更する

Last updated at Posted at 2014-04-13

※ 「テンプレート決定の為の\View::forge()を2回呼ばない方法を探しているんですが、、、」
という方には役に立たない情報です。

fuel/app/classes/views/template.php
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="utf-8">
    <title><?php echo $title; ?></title>
  </head>
  <body>
    <div>
      <?php echo $content; ?>
    </div>
  </body>
</html>
fuel/app/classes/controller/demo.php
/**
 * デモ用
 */
class Controller_Demo extends Controller_Template
{
  /**
   * デフォルト画面
   */
  public function action_sample1()
  {
    $this->template->title   = 'デフォルトのtemplate.phpを使用';
    $this->template->content = ViewModel::forge('demo/sample1');
  }
}

action_sample1内で$this->templateに値を追加出来るのは、
下記の様に\Controller_Template::before()にて$this->template\View::forge()した値を設定しているためです。

fuel/core/classes/controller/template.php
/**
 * Load the template and create the $this->template object
 */
public function before()
{
    if ( ! empty($this->template) and is_string($this->template))
    {
        // Load the template
        $this->template = \View::forge($this->template);
    }
    return parent::before();
}

ですので、action内でテンプレートとして使用するファイルを変更したい場合は、再度$this->template\View::forge()した値を設定してやれば出来ます。

fuel/app/classes/controller/demo.php
/**
 * デモ用
 */
class Controller_Demo extends Controller_Template
{
  /**
   * デフォルト画面
   */
  public function action_sample1()
  {
    $this->template->title   = 'デフォルトのtemplate.phpを使用';
    $this->template->content = ViewModel::forge('demo/sample1');
  }

  /**
   * 別テンプレート画面
   */
  public function action_sample2()
  {
    $this->template = View::forge('other_template.php');

    $this->template->title   = 'other_template.phpを使用';
    $this->template->content = ViewModel::forge('demo/sample2');
  }
}

actionレベルでレイアウトを変える必要がある場合というのを、想像出来ないでいますが(「シングルカラムのレイアウトで進んでいたのに、突然2カラムのレイアウトになる」といった感じですよね?)、そういう場合の参考になれば。

22
26
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
22
26