簡體   English   中英

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

[英]use i18n-2 in node.js outside of res scope

我試圖瞄准所以我可以在被調用的函數中使用i18n。

我有錯誤:

(node:15696) UnhandledPromiseRejectionWarning: TypeError: i18n.__ is not a function

我怎么能讓i18n在函數內部工作而不必在一個req中?

Server.js:

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:

somefunction() {
               message = i18n.__("no_user_to_select") + "???";

}

我該怎么解決這個問題?

如果您仔細閱讀使用Express.js下的文檔,則會清楚地記錄它是如何使用的。 在通過i18n.expressBindi18n綁定到表達應用程序i18n.expressBindi18n可以通過所有快速中間件可用的req對象獲得,例如:

req.i18n.__("My Site Title")

所以somefunction應該是一個中間件,如:

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對象,如:

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

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???
}

許多人不鼓勵使用全球性的。

// 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');

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM