我想知道如何针对不同的语言实现i18n节点(https://github.com/mashpie/i18n-node)
我有一个包含多种语言的下拉菜单,当我选择默认语言以外的其他语言时,文本不会仅更改url更改。
默认语言为英语EN
有效,当我选择中文ZH
时,URL更改了,但是setLocale
不起作用,请检查以下代码
app.js
var express = require('express');
var languageRouter = require('./routes/language');
var i18n = require("i18n");
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'node_modules')));
i18n.configure({
locales:['en', 'zh'],
directory: __dirname + '/locales',
defaultLocale: 'en',
cookie: 'i18n'
});
app.use(i18n.init);
app.use('/:lang', languageRouter);
// language.js
var express = require('express');
var router = express.Router();
var util = require('../util.js');
var i18n = require("i18n");
var getcountries = null;
router.get('/', function (req, res) {
i18n.setLocale(req, locale);
if(getCountries===null){
getCountries={"sg": "Singapore", "th":"Thailand"};
res.render("index.ejs", {i18n: res,countries:getCountries})
}
else{
res.render("index.ejs", {i18n: res,countries:getCountries})
}
}
//index.ejs
<ul>
<li class="nav-item dropdown" style="list-style-type: none;">
<a class="dropdown-item" href="/en">EN</a></li>
<li class="nav-item dropdown" style="list-style-type: none;">
<a class="dropdown-item" href="/zh">ZH</a>
</ul>
<p><%=i18n.__("Welcome")%></p>
// en.json
{
"Welcome": "Hi, welcome to our site",
"Language": "Please choose your language",
"Contact Information" : "1 Elf rd, Unicorn Village, Wonderland, Earth"
}
//zh.json
{
"Welcome": "欢迎",
"Language": "请选择语言",
"Contact Information" : "一号 精灵路, 独角兽村, 幸福国, 地球"
}