i was wondering whats the best way to route to pages in codeigniter? Say for example user wants to route to the index page, but should i create a method in a controller that just fo rthat page, or what is better way?
问题:
回答1:
No need to create separate methods or controllers. Here's how I do it:
class Pages extends CI_Controller {
function _remap($method)
{
is_file(APPPATH.'views/pages/'.$method.'.php') OR show_404();
$this->load->view("pages/$method");
}
}
So the url http://example.com/pages/about
would load the view file application/views/pages/about.php
. If the file doesn't exist, it shows a 404.
You don't need any special routing to do this, but you can do something like this if you wanted the URL to be http://example.com/about
instead:
// Route the "about" page
$route['about'] = "pages/$1";
// Route ALL requests to the static page handler
$route['(:any)'] = "pages/$1";
回答2:
Routing can be done using the application/config/routes.php
file. You can define custom routes redirecting to the index page there. There is absolutly no need to create methods for every page.
A more detailed explanation can be found here: http://codeigniter.com/user_guide/general/routing.html
EDIT: Didn't realy got what you meant, but here is the solution I use:
class Static_pages extends CI_Controller {
public function show_page($page = 'index')
{
if ( ! file_exists('application/views/static_pages/'.$page.'.php'))
show_404();
$this->load->view('templates/header');
$this->load->view('static_pages/'.$page);
$this->load->view('templates/footer');
}
}
I make 1 controller in application/controllers
for the static pages with 1 method in it that I use to load in the static pages.
Then I add this line to application/config/routes.php
:
$route['(:any)'] = 'static_pages/show_page/$1';
//you can also change the default_controller to show this static page controller
$route['default_controller'] = 'static_pages/show_page';
回答3:
In the config file located at /application/config/routes.php