express-view-switcher
![License](https://img.shields.io/github/license/shimataro/express-view-switcher.svg)
switch the view root directory per request
How to install
npm install -S express-view-switcher
Usage
1: for multi-device support
import viewSwitcher from "express-view-switcher";
const app = express();
app.set("view engine", "pug");
app.use(viewSwitcher((req) =>
{
return [["smartphone", "default"]];
}));
2: for multi-language support
app.use(viewSwitcher((req) =>
{
return [["en-us", "en", "ja"]];
}));
3: for both multi-device + multi-language support
app.use(viewSwitcher((req) =>
{
return [
["en-us", "en", "ja"],
["smartphone", "default"],
];
}));
specify root directory
app.use(viewSwitcher((req) =>
{
return [["smartphone", "default"]];
}), "basedir");
Practical example
app.use(viewSwitcher((req) =>
{
return [_getLanguageCandidates(req), _getDeviceCandidates(req)];
}));
function _getRequestHeader(req, name, maxLength = 256)
{
if(!req.headers.hasOwnProperty(name))
{
return "";
}
return req.headers[name].substr(0, maxLength);
}
function _getLanguageCandidates(req)
{
const acceptLanguage = _getRequestHeader(req, "accept-language");
const languageCandidates = [];
for(const language of acceptLanguage.split(","))
{
const parts = language.split(";");
languageCandidates.push(parts[0]);
}
languageCandidates.push("en");
return languageCandidates;
}
function _getDeviceCandidates(req)
{
const userAgent = _getRequestHeader(req, "user-agent");
return [_detectDevice(userAgent), "default"];
function _detectDevice(userAgent)
{
if(userAgent.indexOf("iPhone") !== -1)
{
return "smartphone";
}
if(userAgent.indexOf("iPod touch") !== -1)
{
return "smartphone";
}
if(userAgent.indexOf("iPad") !== -1)
{
return "tablet";
}
if(userAgent.indexOf("Android") !== -1)
{
if(userAgent.indexOf("Mobile") !== -1)
{
return "smartphone";
}
else
{
return "tablet";
}
}
return "default";
}
}
License
MIT License
Copyright
© 2017 shimataro