如何在codeigniter中通过代理自动加载移动模板?

dir:
application
 -controllers 
 -models
 -views
 -mobile_views

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

Check this

You can do it in two way. Way 1: Its very simple. In the above answer (the link I have given) add following line in the end of MyController function

$this->load->_ci_view_path  . = $this->view_type .'/';

You are done. You can simply load view like normal view load.

Way 2: To autoload a view based on user agent, I think you can implement it using hooks. To implement this hooks you need to follow the following steps

  1. Autoload user agent library in autoload.php

    $autoload['libraries'] = array('user_agent');

  2. Enable hooks in config.php

    $config['enable_hooks'] = TRUE;

  3. Not implement hooks on post_controller_constructor. Add following codes to hooks.php

    $hook['post_controller_constructor'][] = array('class' => 'Loadview', 'function' => 'load', 'filename' => 'loadview.php', 'filepath' => 'hooks' );

  4. Now create a page named loadview.php under hooks directory having following code

class Loadview
{

    public static $MOBILE_PLATFORM = 'mobile';
    public static $DEFAULT_PLATFORM = 'default';

    public function load(){
        $this->CI =& get_instance();
        $view_type = $this->CI->agent->is_mobile() ? self::$MOBILE_PLATFORM : self::$DEFAULT_PLATFORM;
        $this->CI->load->_ci_view_path = $this->CI->load->_ci_view_path . $view_type .'/';
    }

}
  1. You are done now. You can simply load view like normal view load.

to load views from another dir aside from "views", i found this forum topic to be helpful

http://codeigniter.com/forums/viewthread/132960/

function external_view($path, $view, $vars = array(), $return = FALSE)
    {
        $full_path = $path.$view.'.php';
        if (file_exists($full_path)) 
        {
            return $this->_ci_load(array('_ci_path' => $full_path, '_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
        }
        else
        {
            show_error('Unable to load the requested module template file: '.$view);
        }
    } 

and you can work the rest from the controller.

I do this in my controller:

public function index()
{   
    if($this->agent->is_mobile())
    {
        $this->load_mobile();   
    }   
    else
    {
        $this->load_web();
    }
}

public function load_mobile()
{
    $this->load->view('mobile/home');
}

public function load_web()
{
    $this->load->view('web/home');
}

In this way I can add different data to mobile and to web pages.

I also extend the default controller and add some useful extra features:

  • Enables the usage of master page/templates.
  • Can add css and javascript files.
  • Uses the _output method for controlling the controllers output.
  • Can load relative content with in the form of modules (views)

So I can manage better the different pages.

Bye!!