Skip to content

Commit 166ebf2

Browse files
committed
add mobile view rednering feature
1 parent 6aeba16 commit 166ebf2

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

index.js

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ var url = require('url')
1414
* @api public
1515
*/
1616

17-
function helpers (name) {
17+
function helpers (name, app) {
1818
return function (req, res, next) {
1919
res.locals.appName = name || 'App'
2020
res.locals.title = name || 'App'
@@ -34,6 +34,33 @@ function helpers (name) {
3434
res.locals.warning = req.flash('warning')
3535
}
3636

37+
/**
38+
* Render mobile views
39+
*
40+
* If the request is coming from a mobile/tablet device, it will check if
41+
* there is a .mobile.ext file and it that exists it tries to render it.
42+
*
43+
* Refer https://github.com/madhums/nodejs-express-mongoose-demo/issues/39
44+
* For the implementation refer the above app
45+
*/
46+
47+
var ua = req.header('user-agent')
48+
var fs = require('fs')
49+
50+
res._render = res.render
51+
req.isMobile = /mobile/i.test(ua)
52+
53+
res.render = function (template, locals, cb) {
54+
var view = template + '.mobile.' + app.get('view engine')
55+
var file = app.get('views') + '/' + view
56+
57+
if (/mobile/i.test(ua) && fs.existsSync(file)) {
58+
res._render(view, locals, cb)
59+
} else {
60+
res._render(template, locals, cb)
61+
}
62+
}
63+
3764
next()
3865
}
3966
}

0 commit comments

Comments
 (0)