-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
80 lines (68 loc) · 1.39 KB
/
app.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
const path = require('path')
const express = require('express')
const handlebars = require('express-handlebars')
const i18n = require('i18n')
const inDev = process.env.NODE_ENV !== 'production'
const routes = require('./routes')
/**
* configure translations
*/
i18n.configure({
locales: ['en', 'nl'],
defaultLocale: 'en',
directory: path.resolve(__dirname, 'translations'),
autoReload: inDev,
updateFiles: inDev,
syncFiles: inDev
})
/**
* create express app
*/
const app = express()
/**
* setup templating
*/
app.engine(
'hbs',
handlebars({
defaultLayout: 'index',
layoutsDir: path.resolve(__dirname, 'views', 'layouts'),
partialsDir: path.resolve(__dirname, 'views', 'partials'),
extname: 'hbs'
})
)
app.set('view engine', 'hbs')
/**
* initialize translations for each request
* guessing browser language by it's header
*/
app.use(i18n.init)
/**
* redirect to guessed language home page
* -> /en will be default
*/
app.all('/', (req, res) => {
res.redirect(`/${i18n.getLocale(req)}`)
})
/**
* add routes with language prefix
*/
app.use('/:lang', routes)
/**
* set language based on prefix path
*/
app.param('lang', (req, res, next, lang) => {
i18n.setLocale(req, lang)
next()
})
/**
* publish current language for html attribute
*/
app.use((req, res, next) => {
res.locals.lang = i18n.getLocale(req)
next()
})
/**
* startup
*/
app.listen(3000)