Php/fuelphp/スマホテンプレ切り替え
提供: 初心者エンジニアの簡易メモ
スマホ判定
以下にあるAgentクラスを作成
- fuel/app/classes/agent.php
http://btt.hatenablog.com/entry/2012/07/04/001254
Agentクラスを自動読み込みするように
- fuel/app/bootstrap.php
Autoloader::add_classes(array( // Add classes you want to override here // Example: 'View' => APPPATH.'classes/view.php', 'Agent' => APPPATH.'classes/agent.php' ));
以下でスマホ判定
if (Agent::is_smartphone()) {}
pc/スマホ切り替え
サンプル
- fuel/app/config/theme.php
return array( 'active' => 'default', 'fallback' => 'default', 'paths' => array( APPPATH.'themes', ), 'assets_folder' => 'assets', 'view_ext' => '.php', 'require_info_file' => false, 'info_file_name' => 'themeinfo.php', 'use_modules' => false, );
- fuel/app/classes/controller/base.php
class Controller_Base extends Controller { protected $theme; public function before() { parent::before(); // スマホ以外 if (!Agent::is_smartphone()) { $this->theme = Theme::instance('pc', array( 'active' => "pc", 'fallback' => 'pc', 'paths' => array(APPPATH . 'themes'), 'view_ext' => '.php', )); $this->theme->set_template('template'); $this->theme->active('pc'); } else { $this->theme = Theme::instance('default', array( 'active' => "default", 'fallback' => 'default', 'paths' => array(APPPATH . 'themes'), 'view_ext' => '.php', )); $this->theme->set_template('template'); $this->theme->active('default'); } } }
- fuel/app/classes/controller/test.php
class Controller_Test extends Controller_Base { public function action_index() { $data = array( 'user' => 'user1', ); $this->theme->template->title = "title1"; $this->theme->template->content = $this->theme->view('test/index', $data); return $this->theme; } }
- fuel/app/themes/default/template.php
<html> <head> <title><?= $title ?></title> </head> <body> default template <?= $content ?> </body> </html>
- fuel/app/themes/default/test/index.php
<p> test/index default theme <?= $user ?> </p>
- fuel/app/themes/pc/template.php
<html> <head> <title><?= $title ?></title> </head> <body> pc template <?= $content ?> </body> </html>
- fuel/app/themes/pc/test/index.php
<p> test/index pc theme <?= $user ?> </p>
テーマテンプレからパーツテンプレを呼び出したい。
- themes/default/test/index.php
<p> test/index theme <?= Theme::instance()->view('test/_content', array('user' => $user)); ?> </p>
- themes/default/test/_content.php
content_part <?= $user ?>
pcとスマホは同じテンプレでデータだけを切り替えたい場合
<? if (Agent::is_smartphone()): ?> スマホ <? else: ?> pc <? endif; ?>