nuxt-i18n
Advanced tools
Comparing version 2.4.1 to 2.5.0
@@ -5,2 +5,12 @@ # Change Log | ||
<a name="2.5.0"></a> | ||
# [2.5.0](https://github.com/nuxt-community/nuxt-i18n/compare/v2.4.1...v2.5.0) (2018-03-10) | ||
### Features | ||
* Browser language detection ([755fa59](https://github.com/nuxt-community/nuxt-i18n/commit/755fa59)), closes [#37](https://github.com/nuxt-community/nuxt-i18n/issues/37) | ||
<a name="2.4.1"></a> | ||
@@ -7,0 +17,0 @@ ## [2.4.1](https://github.com/nuxt-community/nuxt-i18n/compare/v2.4.0...v2.4.1) (2018-03-10) |
@@ -13,3 +13,5 @@ const { resolve } = require('path') | ||
langFiles: {}, | ||
ignorePaths: [] | ||
ignorePaths: [], | ||
detectBrowserLanguage: false, | ||
redirectCookieKey: 'redirected' | ||
} | ||
@@ -16,0 +18,0 @@ const options = merge(defaults, moduleOptions, this.options.i18n) |
@@ -0,4 +1,5 @@ | ||
import cookie from 'cookie'; | ||
import middleware from './middleware' | ||
middleware['i18n'] = function ({ app, route, redirect, error, hotReload }) { | ||
middleware['i18n'] = function ({ app, req, res, route, params, redirect, error, hotReload }) { | ||
const locales = <%= JSON.stringify(options.locales) %> | ||
@@ -17,2 +18,28 @@ const localeCodes = locales.map(l => l.code) | ||
} | ||
// Handle browser language detection | ||
if (<%= options.detectBrowserLanguage %> && req && route.name) { | ||
const cookieKey = '<%= options.redirectCookieKey %>'; | ||
const cookies = cookie.parse(req.headers.cookie); | ||
// Redirect only if cookie not set yet | ||
if (!cookies[cookieKey]) { | ||
const browserLocale = req.headers['accept-language'].split(',')[0].toLocaleLowerCase().substring(0, 2) | ||
// Set cookie | ||
if (res) { | ||
const date = new Date(); | ||
const redirectCookie = cookie.serialize(cookieKey, 1, { | ||
expires: new Date(date.setDate(date.getDate() + 365)) | ||
}) | ||
res.setHeader('Set-Cookie', redirectCookie); | ||
} | ||
// Redirect | ||
if (browserLocale !== app.i18n.locale && localeCodes.indexOf(browserLocale) !== -1) { | ||
app.i18n.locale = browserLocale | ||
redirect(app.localePath(Object.assign({}, route , { | ||
name: app.getRouteBaseName() | ||
}))); | ||
} | ||
} | ||
} | ||
// Get locale from params | ||
@@ -19,0 +46,0 @@ let locale = defaultLocale |
{ | ||
"name": "nuxt-i18n", | ||
"version": "2.4.1", | ||
"version": "2.5.0", | ||
"description": "i18n for Nuxt", | ||
@@ -37,2 +37,3 @@ "license": "MIT", | ||
"dependencies": { | ||
"cookie": "^0.3.1", | ||
"vue-i18n": "^7.3.2", | ||
@@ -39,0 +40,0 @@ "vue-i18n-extensions": "^0.1.0" |
31630
348
3
+ Addedcookie@^0.3.1
+ Addedcookie@0.3.1(transitive)