This repository has been archived by the owner on Sep 28, 2018. It is now read-only.
/
dynamicHelpers.js
140 lines (127 loc) · 2.8 KB
/
dynamicHelpers.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*!
* Sunrise - View dynamicHelper module
* Copyright (c) 2011 Yohei Sasaki <yssk22@gmail.com>
* MIT Licensed
*/
var path = require('path');
var merge = require('./utils').merge;
module.exports = {
/**
* Returns request object
*/
request: function(req, res){
return req;
},
/**
* Returns session object
*/
session: function(req, res){
return req.session;
},
/**
* Returns the user object
*/
currentUser: function(req, res){
return req.currentUser;
},
/**
* Returns true if the current user has logged in.
*/
isLogin: function(req, res){
return req.isLogin;
},
/**
* Returns the absolute URL for the given path
*
* @param {String} path the url path.
* @api public
*/
url: function(req, res){
var base = req.app.set('home');
var secure = req.app.constructor.name == 'HTTPSServer';
return function(p, options){
if( typeof(p) == 'object' ){
options = p;
p = undefined;
}
options = merge({
fromAppRoot: true,
onlyPath: true
}, options);
var s = '';
if( options.onlyPath == false ){
s = (secure ? "https" : "http") + "://" + req.header('host');
}
if( options.fromAppRoot && base != '/' ){
if( base[base.length-1] == '/' ){
s = s + base.substr(0, base.length - 1);
}else{
s = s + base;
}
}
if( p ){
if( p[0] == '/' ){
return s + p;
}else{
return s + path.join(path.dirname(req.url), p);
}
}else{
return s + req.url;
}
};
},
/**
* Returns the translated message for the user locale.
*
* @param {String} msgId message id.
* @api public
*/
_: function(req, res){
return function(msgId){
return req.app.i18n.translate(msgId, req.locales);
};
},
title: function(req, res){
var _ = module.exports._(req, res);
return function(t){
res.local("page").title = _(t);
return t;
};
},
canonical: function(req, res){
return function(url){
res.local("page").canonical = url;
return url;
};
},
feed: function(req, res){
return function(url){
res.local("page").feed = url;
return url;
};
},
js: function(req, res){
return function(){
var list = arguments;
var l = res.local('page').javascripts;
for(var i in list){
var p = list[i];
if( l.indexOf(path) < 0 ){
l.push(path.join(app.route, p));
}
}
};
},
css: function(req, res){
return function(){
var list = arguments;
var l = res.local('page').stylesheets;
for(var i in list){
var p = list[i];
if( l.indexOf(path) < 0 ){
l.push(path.join(app.route, p));
}
}
};
}
};