Authored by 刘传洋

guang begin

/**
* guang controller
* @author: lcy<chuanyang.liu@yoho.cn>
* @date: 2016/08/31
*/
'use strict';
let _ = require('lodash');
class Pagination {
constructor(url, page, totalRecords, pageSize){
constructor() { // url, page, totalRecords, pageSize
let options = {};
let len = arguments.length;
let args = [].slice.call(arguments);
let _pageSize = 0;
if(args.length && _.isPlainObject(args[len - 1])) {
if (args.length && _.isPlainObject(args[len - 1])) {
options = args.pop();
}
this.baseUrl = args.shift() || options.baseUrl;
this.page = args.shift() || 1;
this.totalRecords = args.shift() || 0;
this.totalRecords = args.shift() || 0;
_pageSize = args.shift() || options.pageSize;
this.pageSize = _pageSize || 10;
this.totalPages = options.totalPages || 0;
this.theme = options.theme || 'full';
this.pageVar = options.pageVar || 'page';
this.pageSizeVar = options.pageSizeVar || 'pageSize';
this.theme = options.theme || 'full';
this.pageVar = options.pageVar || 'page';
this.pageSizeVar = options.pageSizeVar || 'pageSize';
if(!this.totalPages && this.totalRecords) {
if (!this.totalPages && this.totalRecords) {
this.totalPages = Math.ceil(this.totalRecords / this.pageSize);
}
this.base = this.baseUrl + (this.baseUrl.indexOf('?') < 0 ? '?' : '&') +
(_pageSize ? (this.pageSizeVar + '=' + this.pageSize + '&') : '') +
this.pageVar + '=';
}
this.base = this.baseUrl + (this.baseUrl.indexOf('?') < 0 ? '?' : '&') +
(_pageSize ? (this.pageSizeVar + '=' + this.pageSize + '&') : '') +
this.pageVar + '=';
}
hasNextPage() {
return this.page < this.totalPages;
... ... @@ -45,4 +53,6 @@ class Pagination {
getUrl(page) {
return this.base + page || 1;
}
}
\ No newline at end of file
}
module.exports = Pagination;
... ...
... ... @@ -6,10 +6,11 @@
'use strict';
const _ = require('lodash');
// const _ = require('lodash');
const channelModel = require('../models/index');
const HeaderModel = require('../../../doraemon/models/header');
// const HeaderModel = require('../../../doraemon/models/header');
exports.index = (req, res, next) => {
... ... @@ -20,53 +21,58 @@ exports.index = (req, res, next) => {
let pathNav = channelModel.getIndexNav(channel);
/*Promise.all([
channelModel.getBanner(),
channelModel.getCategory(),
channelModel.getList(),
//page
channelModel.getHotTags(),
channelModel.getAds(),
channelModel.getExcellectRecos()
]).then(ret => {
res.render('index', {
'guang' : {
'slider' : ret[0],
'msgTypes' : ret[1],
'msgs' : ret[2],
'hotTags' : ret[6],
'ads' : ret[3],
'exRecos' : ret[5],
'msgPager' : null,
'guangIndexPage' : true
}
});
}).catch(next);*/
Promise.all([
channelModel.getBanner(),
channelModel.getCategory(),
channelModel.getList(),
return res.render('index', {
pageName : 'guang-index',
world : {
aaa : 'AAA'
// page
channelModel.getHotTags(),
channelModel.getAds(),
channelModel.getExcellectRecos()
]).then(ret => {
res.render('index', {
guang: {
slider: ret[0],
msgTypes: ret[1],
msgs: ret[2],
hotTags: ret[6],
ads: ret[3],
exRecos: ret[5],
msgPager: null,
guangIndexPage: true,
limit: limit,
type: type,
pathNav: pathNav,
page: page
}
});
}).catch(next);
/* return res.render('index', {
pageName: 'guang-index',
world: {
aaa: 'AAA'
}
});
});*/
}
};
exports.detail = (req, res, next) => {
return res.render('detail', {
detailId : req.params.id
exports.detail = (req, res) => {
return res.render('detail', {
detailId: req.params.id
});
}
};
exports.tags = (req, res, next) => {
exports.tags = (req, res) => {
return res.render('index', {
});
}
};
exports.editor = (req, res, next) => {
exports.editor = (req, res) => {
return res.render('index', {
});
}
};
... ...
... ... @@ -7,43 +7,50 @@
'use strict';
let fs = require('fs');
//exphbs = require('express-handlebars').create(),
//app = express(),
// exphbs = require('express-handlebars').create(),
// app = express(),
function wrap(app, exphbs) {
let vPath = app.get('views') || 'views/',
extName = app.get('view engine') || '.hbs',
Handlebars = exphbs.handlebars;
Handlebars.registerHelper("include", function(partial, options){
Handlebars.registerHelper('include', function(partial, options) {
console.log('-------');
//console.log(exphbs);
console.log(exphbs);
console.log('==================');
console.log(Handlebars.partials);
// console.log(exphbs);
// console.log(exphbs);
// console.log('==================');
// console.log(Handlebars.partials);
let tmpl = Handlebars.partials[partial] || exphbs.partials[partial];
let encoding = options.hash['encoding'] || 'utf8';
exphbs.getPartials().then(function(partials){
// let encoding = options.hash['encoding'] || 'utf8';
exphbs.getPartials().then(function(partials) {
console.log(partials.length);
}).catch(function(){
}).catch(function() {
});
if(tmpl == null) {
var source = fs.readFileSync(`${vPath}/${partial}${extName}`, 'utf8');
if(source != null) {
if (tmpl === null) {
let source = fs.readFileSync(`${vPath}/${partial}${extName}`, 'utf8');
if (source !== null) {
Handlebars.registerPartial(partial, source);
tmpl = Handlebars.partials[partial];
} else {
new Error('partial is not found : ' + partial);
}
}
//options.fn(this);
var ctx = Object.create(this);
for(var i in options.hash) {
ctx[i] = options.hash[i];
// options.fn(this);
let ctx = Object.create(this);
for (let i in options.hash) {
if (options.hash.hasOwnProperty(options.hash[i])) {
ctx[i] = options.hash[i];
}
}
if (typeof tmpl !== 'function') {
tmpl = Handlebars.compile(tmpl);
... ... @@ -53,4 +60,4 @@ function wrap(app, exphbs) {
}
module.exports = wrap;
\ No newline at end of file
module.exports = wrap;
... ...
... ... @@ -9,8 +9,8 @@
let exphbs = require('express-handlebars').create(),
Handlebars = exphbs.handlebars;
Handlebars.registerHelper('json', function(json){
Handlebars.registerHelper('json', function(json) {
return new Handlebars.SafeString(JSON.stringify(json));
});
module.exports = exphbs.handlebars;
\ No newline at end of file
module.exports = exphbs.handlebars;
... ...
... ... @@ -6,149 +6,86 @@
'use strict';
let fs = require('fs'),
let // fs = require('fs'),
_ = require('lodash'),
exphbs = require('express-handlebars').create(),
Handlebars = exphbs.handlebars;/*,
Handlebars = exphbs.handlebars;/* ,
Pagination = require('../common/pagination');
*/
let ALL_TYPES= {
'stand' : 'p-page-n',
'mini' : 'p-n',
'full' : 'f-p-page-n-l-info-input-gobtn',
'fullellipsis' : 'f-p-pe-n-l-info-input-gobtn',
'ellipsis' : 'p-pe-n'
let ALL_TYPES = {
stand: 'p-page-n',
mini: 'p-n',
full: 'f-p-page-n-l-info-input-gobtn',
fullellipsis: 'f-p-pe-n-l-info-input-gobtn',
ellipsis: 'p-pe-n'
};
Handlebars.registerHelper("page", function(){
var options = arguments[arguments.length - 1];
var baseUrl = (arguments.length > 1 ? arguments[0] : null) || options.hash.baseUrl || '',
page = (options.hash.page || 1)*1,
showNum = (options.hash.showNum || 7)*1,
pageSize= options.hash.pageSize || 20,
totalPages = options.hash.totalPages,
Handlebars.registerHelper('page', function() {
let options = arguments[arguments.length - 1];
let baseUrl = (arguments.length > 1 ? arguments[0] : null) || options.hash.baseUrl || '',
page = (options.hash.page || 1) * 1,
showNum = (options.hash.showNum || 7) * 1,
pageSize = options.hash.pageSize || 20,
totalPages = options.hash.totalPages,
totalRecords = options.hash.totalRecords,
theme = options.hash.theme || 'pager',
currentClass = options.hash.currentClass || 'cur',
type = options.hash.type || 'stand', //min full stand ellipsis or: f-首页, p-上一页, page-页码,n-下一页,l-最后一页,info-displayMsg,inout输入框,gobtn-goto Btn
pageVar = options.pageVar || 'page',
pageSizeVar = options.pageSizeVar || "pageSize",
base = baseUrl + (baseUrl.indexOf('?') < 0 ? '?' : '&')
+ (options.hash.pageSize ? (pageSizeVar + '=' + pageSize + '&') : '')
+ pageVar + '=';
if(!totalPages) {
if(!totalRecords || !pageSize) {
return new Handlebars.SafeString("");
} else {
totalPages = Math.ceil(totalRecords / pageSize);
}
}
var items = ALL_TYPES[type] ? ALL_TYPES[type] : type;
items = _.isArray(items) ? items : (items || ALL_TYPES.stand).split('-');
var hasPage = false; //配置中如果配置了多次 page/pe 则将忽略,只第一次有效
var ret = `<div class="pager ${theme}">`;
items.forEach(function(val, index, arr){
switch(val) {
case 'f' :
if(page > 1) {
ret += `<a href="${base}1" title="首页">首页</a>`;
}
break;
case 'p' :
if(page > 1) {
ret += `<a href="${base}` + (page - 1) + `" title="上一页">上一页</a>`;
}
break;
case 'n' :
if(page < totalPages) {
ret += `<a href="${base}` + (page + 1) + `" title="下一页">下一页</a>`;
}
break;
case 'l' :
if(page < totalPages) {
ret += `<a href="${base}${totalPages}" title="尾页">尾页</a>`;
}
break;
case 'info' :
ret += `共{totalRecords}/{totalPages}页`;
break;
case 'input' :
//input
//ret += '<span class="{cls}"><input value="{value}" type="text"></span>';
break;
case 'gobtn' :
//goto btn
break;
case 'page' :
if(!hasPage) ret += createStandItems();
hasPage = true;
break;
case 'pe' :
if(!hasPage) ret += createEllipsisItems();
hasPage = true;
break;
}
});
function createStandItems(){
return renderItem(getPageNums());
}
function createEllipsisItems(){
return renderItem(getPageNums('e'));
}
// min full stand ellipsis or: f-首页, p-上一页, page-页码,n-下一页,l-最后一页,info-displayMsg,inout输入框,gobtn-goto Btn
type = options.hash.type || 'stand',
pageVar = options.pageVar || 'page',
pageSizeVar = options.pageSizeVar || 'pageSize',
base = baseUrl + (baseUrl.indexOf('?') < 0 ? '?' : '&') +
(options.hash.pageSize ? (pageSizeVar + '=' + pageSize + '&') : '') +
pageVar + '=';
function getPageNums(type){
function getPageNums(ntype) {
var pageNums = [];
var num = showNum;
if(type == 'e') {
if (ntype === 'e') {
num = num - 2;
num = num > 2 ? num : 2;
}
/** 分页展示页码个数begin 规则:展示最靠近当前页的指定个数 **/
var pageShowMax = num % 2 == 0 ? page - 1 : page;
var pageShowMin = page;
let pageShowMax = num % 2 === 0 ? page - 1 : page;
let pageShowMin = page;
for(var i = 0; i < Math.floor(num/2); i++) {
for (let i = 0; i < Math.floor(num / 2); i++) {
pageShowMax++;
pageShowMin--;
if(pageShowMax > totalPages) {
if (pageShowMax > totalPages) {
pageShowMax = totalPages;
if(pageShowMin > 1) {
if (pageShowMin > 1) {
pageShowMin--;
}
}
if(pageShowMin < 1) {
if (pageShowMin < 1) {
pageShowMin = 1;
if(pageShowMax < totalPages) {
if (pageShowMax < totalPages) {
pageShowMax++;
}
}
}
for(var n = pageShowMin; n <= pageShowMax; n++) {
for (let n = pageShowMin; n <= pageShowMax; n++) {
pageNums.push(n);
}
if(type == 'e') {
if(pageShowMin > 3) {
if (ntype === 'e') {
if (pageShowMin > 3) {
pageNums.unshift(1, '.');
} else if(pageShowMin == 2){
} else if (pageShowMin === 2) {
pageNums.unshift(1);
} else if(pageShowMin == 3) {
} else if (pageShowMin === 3) {
pageNums.unshift(1, 2);
}
if(pageShowMax < totalPages - 2) {
if (pageShowMax < totalPages - 2) {
pageNums.push('.', totalPages);
} else {
for(var x = pageShowMax + 1; x <= totalPages; x++) {
for (let x = pageShowMax + 1; x <= totalPages; x++) {
pageNums.push(x);
}
}
... ... @@ -159,14 +96,16 @@ Handlebars.registerHelper("page", function(){
function renderItem(arr) {
/** 分页展示页码个数end **/
var ret = '';
if(_.isArray(arr) && arr.length) {
let ret = '';
if (_.isArray(arr) && arr.length) {
arr.forEach((val, index, arrs) => {
if('.' == val) {
arr.forEach((val) => {
if (val === '.') {
ret += '<a>...</a>';
} else {
ret += `<a href="${base}${val}" ` + (page === val ? `class="${currentClass}"` : '') + ` title="第${val}页">${val}</a>`;
ret += `<a href="${base}${val}" ` +
(page === val ? `class="${currentClass}"` : '') +
` title="第${val}页">${val}</a>`;
}
});
}
... ... @@ -174,11 +113,80 @@ Handlebars.registerHelper("page", function(){
return ret;
}
if(options.fn) {
function createStandItems() {
return renderItem(getPageNums());
}
function createEllipsisItems() {
return renderItem(getPageNums('e'));
}
if (!totalPages) {
if (!totalRecords || !pageSize) {
return new Handlebars.SafeString('');
} else {
totalPages = Math.ceil(totalRecords / pageSize);
}
}
let items = ALL_TYPES[type] ? ALL_TYPES[type] : type;
items = _.isArray(items) ? items : (items || ALL_TYPES.stand).split('-');
let hasPage = false; // 配置中如果配置了多次 page/pe 则将忽略,只第一次有效
let ret = `<div class="pager ${theme}">`;
items.forEach(function(val) {
switch (val) {
case 'f' :
if (page > 1) {
ret += `<a href="${base}1" title="首页">首页</a>`;
}
break;
case 'p' :
if (page > 1) {
ret += `<a href="${base}` + (page - 1) + '" title="上一页">上一页</a>';
}
break;
case 'n' :
if (page < totalPages) {
ret += `<a href="${base}` + (page + 1) + '" title="下一页">下一页</a>';
}
break;
case 'l' :
if (page < totalPages) {
ret += `<a href="${base}${totalPages}" title="尾页">尾页</a>`;
}
break;
case 'info' :
ret += '共{totalRecords}条/{totalPages}页';
break;
case 'input' :
// input
// ret += '<span class="{cls}"><input value="{value}" type="text"></span>';
break;
case 'gobtn' :
// goto btn
break;
case 'page' :
if (!hasPage) {
ret += createStandItems();
}
hasPage = true;
break;
case 'pe' :
if (!hasPage) {
ret += createEllipsisItems();
}
hasPage = true;
break;
}
});
if (options.fn) {
ret += options.fn(options.context);
}
ret += '</div>';
return new Handlebars.SafeString(ret);
});
exports = exphbs.handlebars;
\ No newline at end of file
exports = exphbs.handlebars;
... ...
... ... @@ -10,24 +10,26 @@ let exphbs = require('express-handlebars').create();
let Handlebars = exphbs.handlebars;
let fs = require('fs');
Handlebars.registerHelper('tpl', function(id, file, options){
Handlebars.registerHelper('tpl', function(id, file, options) {
if(options.fn) {
}
var source = Handlebars.partials[file];
var tpl = '';
if(source == null) {
var source = fs.readFileSync('views/' + file + '.html', 'utf8');
if(!source) {
new Error('file is not found : ' + file);
let tpl = '';
if (options.fn) {
tpl = options.fn(this);
} else {
let source = Handlebars.partials[file];
if (source === null) {
source = fs.readFileSync('views/' + file + '.html', 'utf8');
if (!source) {
new Error('file is not found : ' + file);
}
}
tpl += '<script id="' + id + '" type="text/x-handlebars" data-file="' + file + '">';
tpl += source;
tpl += '</script>';
}
tpl += '<script id="' + id + '" type="text/x-handlebars" data-file="'+file+'">';
tpl += source;
tpl += '</script>';
return new Handlebars.SafeString(tpl);
});
module.exports = Handlebars;
\ No newline at end of file
module.exports = Handlebars;
... ...
... ... @@ -6,8 +6,9 @@
var express = require('express'),
path = require('path'),
hbs = require('express-handlebars'),
glob = require("glob");
hbs = require('express-handlebars');
// glob = require('glob');
var app = express();
... ... @@ -21,7 +22,7 @@ app.on('mount', function(parent) {
Object.assign(app.locals, parent.locals);
});
var mhbs = hbs.create({
let mhbs = hbs.create({
extname: '.hbs',
defaultLayout: 'layout',
layoutsDir: doraemon,
... ... @@ -32,13 +33,13 @@ var mhbs = hbs.create({
app.set('views', path.join(__dirname, 'views/action'));
app.engine('.hbs', mhbs.engine);
//register helper
//var helpersDir = path.join(__dirname, 'helpers');
// register helper
// var helpersDir = path.join(__dirname, 'helpers');
// glob.sync(helpersDir + '/**/*.+(js|coffee)').forEach(function(file) {
// console.log(file);
// require(file);
// })
//require('./helpers/include')(app, mhbs);
// require('./helpers/include')(app, mhbs);
require('./helpers/json');
require('./helpers/page');
require('./helpers/tpl');
... ...
... ... @@ -7,17 +7,15 @@
const _ = require('lodash');
const dataMap = require('../../../config/data-map');
// const dataMap = require('../../../config/data-map');
const helpers = global.yoho.helpers;
const processProduct = require(`${global.utils}/product-process`).processProduct;
const serviceApi = global.yoho.ServiceAPI;
const searchApi = global.yoho.SearchAPI;
const headerModel = require('../../../doraemon/models/header');
// const searchApi = global.yoho.SearchAPI;
// const headerModel = require('../../../doraemon/models/header');
... ... @@ -60,7 +58,7 @@ const getHomeChannelNav = (channel) => {
name: `${channel.toUpperCase()}首页`,
pathTitle: 'YOHO!有货'
};
}
};
const getIndexNav = (channelType) => {
... ... @@ -68,11 +66,11 @@ const getIndexNav = (channelType) => {
getHomeChannelNav(channelType),
[{
name: '逛',
pathTitle : '逛',
href : helpers.urlFormat('guang', '', 'guang')
pathTitle: '逛',
href: helpers.urlFormat('guang', '', 'guang')
}]
)
}
);
};
/**
* 获取页文章数据
... ... @@ -80,8 +78,8 @@ const getIndexNav = (channelType) => {
* @return {Object}
*/
const getList = channelType => {
}
return channelType;
};
/**
* 获取热门标签数据
... ... @@ -92,8 +90,8 @@ const getHotTags = (page, limit) => {
let data = {
client_type: 'web',
page : page || 1,
limit : limit || 10
page: page || 1,
limit: limit || 10
};
return serviceApi.get('guang/api/v2/article/getTagTop', data, {
... ... @@ -103,12 +101,12 @@ const getHotTags = (page, limit) => {
let tags = (res && res.data) || [];
return _.map(tags, it => {
return {
tagName : it.tag_name,
url : helpers.urlFormat('/tags/', it.tag_name, 'guang')
}
tagName: it.tag_name,
url: helpers.urlFormat('/tags/', it.tag_name, 'guang')
};
});
});
}
};
/**
* 获取广告数据
... ... @@ -116,8 +114,8 @@ const getHotTags = (page, limit) => {
* @return {Object}
*/
const getAds = channelType => {
}
return channelType;
};
/**
* 获取热门标签数据
... ... @@ -125,16 +123,20 @@ const getAds = channelType => {
* @return {Object}
*/
const getBanner = channelType => {
}
return channelType;
};
const getCategory = channelType => {
}
return channelType;
};
const getExcellectRecos = (channelType, start, limit) => {
}
return {
channelType: channelType,
start: start,
limit: limit
};
};
module.exports = {
... ... @@ -144,5 +146,5 @@ module.exports = {
getBanner: getBanner,
getCategory: getCategory,
getExcellectRecos: getExcellectRecos,
getIndexNav : getIndexNav
}
getIndexNav: getIndexNav
};
... ...
... ... @@ -14,5 +14,5 @@ module.exports = app => {
app.use('/product', require('./apps/product')); // 商品相关页面
app.use(require('./apps/passport')); // 登录注册
app.use('/home', require('./apps/home')); // 会员中心
app.use('/guang', require('./apps/guang'))
app.use('/guang', require('./apps/guang'));
};
... ...