首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在res范围之外的node.js中使用i18n-2

在res范围之外的node.js中使用i18n-2
EN

Stack Overflow用户
提问于 2019-04-04 03:08:48
回答 1查看 1K关注 0票数 5

我正在尝试瞄准,这样我就可以在被调用的函数中使用i18n。

我有一个错误:

代码语言:javascript
复制
(node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function

我怎样才能让i18n在函数中工作,而不是在请求中?

Server.js:

代码语言:javascript
复制
var    i18n = require('i18n-2');

global.i18n = i18n;
i18n.expressBind(app, {
    // setup some locales - other locales default to en silently
    locales: ['en', 'no'],
    // change the cookie name from 'lang' to 'locale'
    cookieName: 'locale'
});

app.use(function(req, res, next) {
    req.i18n.setLocaleFromCookie();
    next();
});

//CALL another file with some something here.

otherfile.js:

代码语言:javascript
复制
somefunction() {
               message = i18n.__("no_user_to_select") + "???";

}

我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-13 01:39:53

如果您仔细阅读Using with Express.js下的文档,就会清楚地了解它是如何使用的。在通过i18n.expressBindi18n绑定到express应用程序之后,所有express中间件都可以通过req对象使用i18n

代码语言:javascript
复制
req.i18n.__("My Site Title")

所以somefunction应该是一个中间件,如下所示:

代码语言:javascript
复制
function somefunction(req, res, next) {
  // notice how its invoked through the req object
  const message = req.i18n.__("no_user_to_select") + "???";
  // outputs -> no_user_to_select???
}

或者,您需要通过中间件显式地传递req对象,例如:

代码语言:javascript
复制
function somefunction(req) {
  const message = req.i18n.__("no_user_to_select") + "???";
  // outputs -> no_user_to_select???
}

app.use((req, res, next) => {
  somefunction(req);
});

如果您想要直接使用i18n,则需要按照文档所示对其执行instantiate操作,如下所示

代码语言:javascript
复制
const I18n = require('i18n-2');

// make an instance with options
var i18n = new I18n({
    // setup some locales - other locales default to the first locale
    locales: ['en', 'de']
});

// set it to global as in your question
// but many advise not to use global
global.i18n = i18n;

// use anywhere
somefunction() {
  const message = i18n.__("no_user_to_select") + "???";
  // outputs -> no_user_to_select???
}

许多人不鼓励使用global。

代码语言:javascript
复制
// international.js
// you can also export and import
const I18n = require('i18n-2');

// make an instance with options
var i18n = new I18n({
    // setup some locales - other locales default to the first locale
    locales: ['en', 'de']
});

module.exports = i18n;

// import wherever necessary
const { i18n } = require('./international');
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55502598

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档