【问题标题】:Optional locale parameter expressjs可选的语言环境参数 expressjs
【发布时间】:2015-12-11 15:19:31
【问题描述】:

我想在我的网址中添加一个可选的语言环境参数,如下所示:

  • domain.tld/ => 最受支持的语言环境
  • domain.tld/fr/ => 强制“fr”作为语言环境

所以,我做了这样的事情:

app.use("/:locale?/", routes.Index);

但我在尝试获取 domain.tld/register/ 时遇到问题,因为“注册”被认为是所要求的语言环境。

有没有人有这样做的想法?

谢谢。

【问题讨论】:

标签: node.js express internationalization


【解决方案1】:

如果有人想知道我做了什么,这是我的快速中间件:

"use strict";

var locale = require("locale");
module.exports = function (supportedLanguages, defaultLocale) {

    // Creation of the list of supported locales
    var supportedLocales = new locale.Locales(supportedLanguages);
    locale.Locale.default = defaultLocale;

    return function (req, res, next) {
        var matches,
            askedLocale = null,
            bestLocale = null,
            locales = null,
            url = null;
        // Test if locale in url 
        matches = req.url.match(/^\/([a-zA-Z]{2})([\/\?].*)?$/i);
        // If locale defined in url
        if (matches !== null) {
            // Get locale
            askedLocale = matches[1].toLowerCase();
            // Modify url for express logic
            req.url = matches[2] || '/';
        }
        // If the asked locale is supported
        if (askedLocale !== null && supportedLanguages.indexOf(askedLocale) !== -1) {
            locales = new locale.Locales(askedLocale);
        } else {
            // Get locale from headers
            locales = new locale.Locales(req.headers["accept-language"]);
        }
        // Getting the best supported locale
        bestLocale = locales.best(supportedLocales).toString();
        // If the asked locale is not the best supported
        if (askedLocale !== null && askedLocale !== bestLocale) {
            // Creation of the new url
            url = "https://" + req.headers.host + "/" + bestLocale + req.url;
            // Redirection to the new locale
            res.redirect(302, url);
        } else {
            // Else if already best locale
            req.setLocale(bestLocale);
            res.locals.locale = req.getLocale();
            // Continue
            next();
        }
    };
};

我这样称呼它:

// Internationalization
app.use(i18n.init);
app.use(localeRedirection(supportedLocales, defaultLocale));

将“supportedLocales”作为语言环境数组,将“defaultLocale”作为默认语言环境。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-18
    • 2020-04-01
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    相关资源
    最近更新 更多