gpt4 book ai didi

javascript - 如何在nodejs koa2和ejs中支持多语言

转载 作者:行者123 更新时间:2023-11-30 20:33:00 24 4
gpt4 key购买 nike

我尝试写一个网页,它应该支持多国语言,在index.js

const Koa = require('koa');
const views = require('koa-views');
const path = require('path');
app.use(views(path.join(__dirname, './view'), {
extension: 'ejs'
}));

app.use( async ( ctx ) => {
let title;
//some codes
if(language == "en") { //if the language is English
title="Title";
}
else if(language == "de") { //if the language is German
title="Titel";
}
await ctx.render('index', {
title
});
});
app.listen(3000, ()=>{
console.log('app runs on port 3000');
});

index.ejs

 <%=title%>

然后我运行这段代码,它会显示很好,现在我想在这个项目中添加一个语言包,比如language.json

{
"en": {
"site": {
"title": "Title"
}
},
"de": {
"site": {
"title": "Titel"
}
}
}

那么index.jsindex.ejs应该怎么改呢?

最佳答案

const Koa = require('koa');
const views = require('koa-views');
const path = require('path');
app.use(views(path.join(__dirname, './view'), {
extension: 'ejs'
}));



const siteTitleLibrary = {
"en": {
"site": {
"title": "Title"
}
},
"de": {
"site": {
"title": "Titel"
}
}
};
// or
// const siteTitleLibrary = require('language.json');

app.use( async ( ctx ) => {
await ctx.render('index', {
site: siteTitleLibrary[language]
});
});
app.listen(3000, ()=>{
console.log('app runs on port 3000');
});

然后在你的 ejs 中使用 <%=site.title%>

关于javascript - 如何在nodejs koa2和ejs中支持多语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50139568/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com