FuelPHPで端末によって表示を切り替える方法はいくつかあるようですが、
一番簡単なのは Themeクラスを使うことです。
今回の要件は下記の通り。
fuel + app + classes | + controller | + list.php ←コントローラー | + view + template_pc.php ←PC用テンプレート + template_mobile.php ←携帯用テンプレート + pc ←PC用テーマディレクトリ | + list | + index.php | + mobile ←携帯用テーマディレクトリ + list + index.php
まずは初期化部分。
class Controller_List extends Controller{ function before(){ parent::before(); // テーマ設定 $this->theme = Theme::instance( 'custom', array( 'active' => "pc", // 存在するテーマディレクトリを指定 'fallback' => 'pc', // activeが存在しない場合に使うテーマ 'paths' => array(APPPATH.'views'), // 検索パス 'view_ext' => '.php' // テーマファイル拡張子 ) ); // モバイル端末ならテンプレート変更 // iPadは除外 if (Agent::browser() != "iPad" && Agent::is_mobiledevice()){ $this->theme->active('mobile'); $this->theme->set_template('template_mobile'); }else{ $this->theme->active('pc'); $this->theme->set_template('template_pc'); } }
いったんインスタンスを作る時に active を指定しないとエラーになるので、
PC向けのテーマ(active)を指定して、後から変更しています。
FuelPHPの Agentクラスでは iPadもモバイル端末扱いなのですが、
iPadは PCと同じほうがいいですよねw
続いて表示部分。
public function action_index() { $this->theme->template->title = "ページタイトル"; $this->theme->template->content = $this->theme->view('list/index', Array( 'hoehoe' => 'ほえほえ' )); return $this->theme; }
タイトルと、テーマ内で使う変数を指定しています。
最後にテーマを返すことで表示させます。
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title><?php echo $title; ?></title> </head> <body> <?php echo $content; ?> <p>PC用</p> </body> </html>
リスト表示するテーマ <?php echo $hoehoe; ?>
このへんを参考にしました。
≫FuelPHPのテーマクラスのサンプル - BTT's blog
≫FuelPHPのテーマクラス | WinRoad徒然草
この記事のサンプルでは Controllerクラスを継承した方法を使っていますが、Controllerクラスを拡張した Controller_Templateを使う方法もあります。
テンプレートコントローラーでは変数「$template」でテンプレートを指定することが出来ます。
class Controller_Entry extends Controller_Template{ public $template = 'template_pc';
画面の反映はテーマを使ったのと同じ様なものです。
サンプルでは Controllerクラスを継承していたので return で表示内容を返す必要がありましたが、Controller_Templateクラスを継承している場合その必要はありません。
$this->template 内のものが自動的に表示されます。
$this->template->content = $this->Theme->view( 'list/index', array('hoehoe'=>'ほえほえ') );
テーマの設定を使って切り替える方法もあるようです。
No comments yet.