我有一个方法news()
,它有两个可选参数 - $category
& $slug
。
新闻页面需要显示所有未分类的新闻文章的分页列表(类别页面(设置为$category
)将需要执行相同的操作,但对于分类的子集)。
因此,似乎标准分页不起作用,因为第二个URI段被视为$category
的{{1}}参数。是否可以解决这个问题,如果它不是一个整数,可能将第二个URI段视为$ category参数,如果是,则将分页参数视为?
以下是相关代码:
控制器
news()
为了尝试整理网址,我还使用了路由:
routes.php文件
function news($category = null, $slug = null) {
if($category == null) { // Get the standard "news" page
// Define the pagination config
$config = array();
$config['base_url'] = base_url() . 'news/';
$config['total_rows'] =$this->post_model->count_posts('NWS');
$config['per_page'] = 3;
$config['uri_segment'] = 2;
$config['use_page_numbers'] = TRUE;
$this->load->library('pagination');
$this->pagination->initialize($config);
// Set the page info
$page = ($this->uri->segment(2)) ? $this->uri->segment(2) : 0;
$data['newsPosts'] = $this->post_model->get_post_list_excerpt('NWS',$config['per_page'], $page);
$data['links'] = $this->pagination->create_links();
$this->template->load('default', 'newsview', $data);
}
elseif($slug == null) {
// Get the page specific to the chosen category
}
}
有没有办法解决我想做的事情/甚至可能吗?我想避免必须使用单独的方法/控制器(如可能的话$route['news'] = 'site/news';
$route['news/(:any)'] = 'site/news/$1';
$route['news/(:any)/(:any)'] = 'site/news/$1/$2';
答案 0 :(得分:0)
好的,这是你可以考虑的一些建议。
base_url("site/news/");
代替base_url() . 'news/';
来澄清您的代码。在这种情况下使用news/(:any)/(:any)
正则表达式是不明确/不正确的,因为第一个(:any)
模式已经包含了其余所有网址。我的意思是:
example.com/site/news/12/file
$ route ['news /(:any)'] ='site / news / $ 1';
$1
将与 12 / file
$ route ['news /(:any)/(:any)'] ='site / news / $ 1 / $ 2';
$1
将匹配: 12 / file
$2
将匹配:(没有)
您可以考虑使用某些特定的通配符,并为您的网址提供额外的安全性:
注意:请记住将规则从最长到最短应用:
$route['news/(:num)/([a-z]+)'] = 'site/news/$1/$2';
$route['news/(:num)'] = 'site/news/$1';
$route['news'] = 'site/news';
现在,回到最初的问题,我认为你可以反转这些参数让category
为最后一个。我们来看看:
$config['base_url'] = base_url("news/category/subset");
$config['uri_segment'] = 4;
看看这个:
public function news($category = false, $subset = false, $page = 1)
{
$this->load->library('pagination');
//checks if category is the page number
if ((string)(int)$category === $category)
{
//ok, there is not category neither subset
$config['base_url'] = base_url('site/news');
$config['uri_segment'] = 3;
}
//checks if subset is the page number
else if ((string)(int)$subset === $subset)
{
$config['base_url'] = base_url('site/news/' . $category);
$config['uri_segment'] = 4;
}
//by elimination, all the three parameters are presents
else
{
//ok, both are presents
$config['base_url'] = base_url('site/news/' . $category . '/' . $subset);
$config['uri_segment'] = 5;
}
$config['total_rows'] = 200;
$config['per_page'] = 20;
$this->pagination->initialize($config);
// more stuff here
}
此分页配置应适用于以下网址:
和页码: