久しぶりのネタもFuelPHPですが
FuelPHPのThemeクラスを使うとPC/モバイルのテーマを簡単に切り替えることができます。
参考になる記事がほかにも色々ありますが、ざっくり紹介まで。
ディレクトリ構成は以下
app + classes + controller + sample.php + config + theme.php + views + template_pc.php + template_mobile.php + pc + top + index.php + header.php + mobile + top + index.php + header.php + elements + footer.php
概略を言うと「template_pc.php」と「template_mobile.php」がテーマ用のテンプレートファイルです。
views内の「pc」と「mobile」とありますがこれがテーマ用のディレクトリとなります。
テーマのディレクトリは変更することができます。
また、モバイル判定後、テーマを変更するだけなのでコントローラは1つです。
それではさっそく例を。
まず設定を行います。
app/config/theme.phpを作成
<?php return array( 'active' => 'pc', // 有効なテーマ 'fallback' => 'pc', // active themeが見つからない場合 'paths' => array(APPPATH.'views'), // テーマのディレクトリ 'view_ext' => '.php', // テーマファイルの拡張子 );
次にコントローラ。
app/controller/sample.php
<?php
class Controller_Sample extends Controller
{
public function before()
{
parent::before();
// Themeインスタンスの生成
$this->theme = Theme::instance();
// モバイル判定を行いテーマを切り替える
if (Agent::is_mobiledevice()) {
$this->theme->active('mobile');
$this->theme->set_template('template_mobile');
} else {
$this->theme->active('pc');
$this->theme->set_template('template_pc');
}
$this->theme->set_partial('header', 'header');
}
public function after($response)
{
if (empty($response) or !$response instanceof Response) {
$response = Response::forge($this->theme->render());
}
return parent::after($response);
}
public function action_index()
{
$posts = Model_Post::find('all');
$view = $this->theme->view('top/index');
$view->set('posts', $posts);
$this->theme->template->content = $view;
}
}
あらかじめbeforeでThemeインスタンスを生成します。
モバイルの判定はAgent::is_mobiledevice()で行い有効なテーマを切り替えます。
※
Agent::is_mobiledevice()は前にも記事にしたようにiPadなどはモバイルとして認識されているようなので注意が必要です。
アクションメソッドはほぼそのままですが
ビューを生成するところでテーマ内のビューを参照します。
beforeの部分で有効なテーマを切り替えているので'top/index'と指定するだけで
PCならpc/top/index、mobileならmobile/top/indexを参照してくれます。
あとはビューです。が、これはもうそのままです。
まず、app/views/template_pc.php
<!doctype html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>PC Site</title>
</head>
<body>
<?php echo $partials['header']; ?>
<?php echo $content; ?>
<?php echo render('elements/footer'); ?>
</body>
</html>
テーマごとに部品化したいものはpartialを使うこともできますし
テーマを無視して部品化するものはrenderなど書く事もできます。
久しぶりに書いてもざっくりとした内容でした。