当前位置: 首页 > 文档资料 > FuelPHP 中文文档 >

樣板控制器 - 一般

优质
小牛编辑
113浏览
2023-12-01

样板控制器是什幺?

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>
		<h1><?php echo $title; ?></h1>

		<div>
<?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));
	}
}