樣板控制器

樣板控制器是什么?

Template 控制器是 Base 控制器的擴充并內建支援樣板。它使用一些預定義的 before() 和 after() 方法。基本上, 它可以用來在你的檢視佈局中包裹頁眉、頁腳、側邊欄等。

使用樣板控制器

如同所有的控制器,你在 fuel/app/classes/controller 目录裡建立一个类別。它們需要擴充 Controller_Template 类別并且預設前綴为 "Controller_"。下面是一个控制器 "example" 的範例:

請注意:預設情況下,擴充 Controller_Template 的类別的所有方法将使用該樣板。
但是,有可能從樣板省略方法

class Controller_Example extends Controller_Template
{
	public function action_index()
	{
		$data = array();
		$this->template->title = 'Example Page';
		$this->template->content = View::forge('test/index', $data);
	}
}

使用樣板控制器的 before() 及/或 after()

請注意:如果你在你的樣板控制器擴充中使用 before() 方法,你 必須 添加 parent::before(); 到該方法,否則 $this->template 将無法使用。 让 after() 兼容 於 Controller_Template: 使用 after($response) 而不僅僅是 after()。

class Controller_Example extends Controller_Template
{
	/**
	 * 你的 before 方法
	 */
	public function before()
	{
		parent::before(); // 沒有这一行,樣板不会運作!

		// 做點什么
	}

	/**
	 * 透過添加 $response 做为一个參数让 after() 兼容於 Controller_Template
	 */
	public function after($response)
	{
		$response = parent::after($response); // 如果你建立自己的 Response 物件就不需要

		// 做點什么

		return $response; // 確認 after() 回傳 Response 物件
	}

	public function action_index()
	{
		$data = array();
		$this->template->title = 'Example Page';
		$this->template->content = View::forge('test/index', $data);
	}
}

樣板範例

樣板档案是一个呼叫你的 JS、CSS、組織你的 HTML 和呼叫檢視局部的好地方。它能让你組織你的輸出。 它就只是一个檢視档案,預設情況下,将注視这裡:fuel/app/views/template.php

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title><?php echo $title; ?></title>

	<?php echo Asset::css('main.css'); ?>
</head>
<body>
	<div id="wrapper">
		<h1><?php echo $title; ?></h1>

		<div id="content">
			<?php echo $content; ?>
		</div>
	</div>
</body>
</html>

變更預設樣板档案

你可以輕易地把預設档案 APPPATH/views/template.php 改为其他的。
你必須把公開變数 $template(注意:在这裡你不需要副档名)設为其他的,例如:

class Controller_Example extends Controller_Template
{

    public $template = 'template_admin';

    public function action_index()
    {
        $this->template->title = 'Example Page';
        $this->template->content = View::forge('test/index', $data);
    }
}

從樣板控制器省略方法

預設情況下,擴充 Controller_Template 的类別的所有方法将使用該樣板。
如果你想要從樣板省略方法,你可以透過在 Response 物件回傳其他東西辦到。那将覆寫預設樣板輸出。

class Controller_Example extends Controller_Template
{
	public $template = 'template_admin';

	public function action_index()
	{
		$this->template->title   = 'Example Page';
		$this->template->content = View::forge('test/index', $data);

		// 这将在樣板顯示內容
	}

	public function action_example()
	{
		$data['title']   = "Example Page";
		$data['content'] = "Don't show me in the template";

		// 優先回傳 Response 物件并将不经樣板顯示內容
		return new Response(View::forge('index/test', $data));
	}
}