*/
var router=express.Router();
/*每頁條數(shù)*/
var pageSize=4;
/*首頁*/
router.get('http://www.3lian.com/',function(req,res,next){
var cid=0;
F.model("article").assignIndexData(cid,1,pageSize,res);
});
/*首頁分頁*/
router.get('/index/:page',function(req,res,next){
var currentPage=parseInt(req.params.page);
var cid=0;
F.model("article").assignIndexData(cid,currentPage,pageSize,res);
});
分類列表分頁路由::8888/category/分類id/分頁
/*分類頁*/
router.get('/category/:cid/:page',function(req,res,next){
var cid=req.params.cid;
var currentPage=parseInt(req.params.page);
F.model("article").assignIndexData(cid,currentPage,pageSize,res);
});
模型數(shù)據(jù)部分
控制器調(diào)用article模型的assignIndexData()方法,參數(shù):分類id,當前頁,每頁條數(shù),響應對象
調(diào)用category模型的getAllList()方法得到分類list,參數(shù):回調(diào)函數(shù)
調(diào)用article模型的getCount()方法得到總條數(shù),參數(shù):分類id,回調(diào)函數(shù)
調(diào)用article模型的getArticlePager()方法得到文章對象的數(shù)據(jù)list,參數(shù):分類id,當前頁,每頁條數(shù),回調(diào)函數(shù)
對上一頁,下一頁進行-1和+1,并進行判斷,上一頁應大于0,下一頁應小于等于總頁數(shù)(總條數(shù)/每頁條數(shù) 向上取整)
把數(shù)據(jù)分配到模板上
/**
* 文章模型文件
*/
module.exports={
/*獲取條數(shù)*/
getCount:function(categoryId,callback){
var condition="";
if(categoryId!=0){
condition="where category_id="+categoryId;
}
var sql="select count(*) num from article "+condition;
db.query(sql,callback);
},
/*獲取分頁數(shù)據(jù)*/
getArticlePager:function(categoryId,currentPage,pageSize,callback){
if(currentPage<=0||!currentPage) currentPage=1;
var start=(currentPage-1)*pageSize;
var end=pageSize;
var condition="";
if(categoryId!=0){
condition="where category_id="+categoryId;
}
var sql="select * from article "+condition+" order by time desc limit "+start+","+end;
db.query(sql,callback);
},
/*歸檔*/
getArchives:function(callback){
db.query("select time from article order by time desc",callback);
},
/*分配首頁數(shù)據(jù)*/
assignIndexData:function(cid,currentPage,pageSize,res){
var categoryModel=F.model("category");
var articleModel=this;
// 分類數(shù)據(jù)
categoryModel.getAllList(function(err,categoryList){
// 文章條數(shù)
articleModel.getCount(cid,function(err,nums){
// 文章分頁
articleModel.getArticlePager(cid,currentPage,pageSize,function(err,articleList){
var nextPage=(currentPage+1)>=Math.ceil(nums[0].num/pageSize) ? Math.ceil(nums[0].num/pageSize) : currentPage+1;
var prePage=(currentPage-1)<=0 ? 1 : currentPage-1;
// 歸檔
articleModel.getArchives(function(err,allArticleTime){
var newArticleTime=[];
for(var i=0;i
newArticleTime.push(F.phpDate("y年m月",allArticleTime[i].time));
}
/*分配數(shù)據(jù)*/
var data={
categoryList:categoryList,
articleList:articleList,
cid:cid,
nextPage:nextPage==0 ? 1 : nextPage,
prePage:prePage,
allArticleTime:newArticleTime,
currentPage:currentPage
};
/*渲染模板*/
res.render("home/index",data);
});
});
});
});
}
};
模板部分
href="/category//index/" rel="external nofollow" >上一頁
href="/category//index/" rel="external nofollow" >下一頁
效果圖: