I try to write a web page, and it should support multi-language, in 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');
});
And the index.ejs
<%=title%>
and I run this code, it will show well, and now I want to add a language package, such as language.json
to this project
{
"en": {
"site": {
"title": "Title"
}
},
"de": {
"site": {
"title": "Titel"
}
}
}
So how should I change in index.js
and index.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');
});
then in your ejs use <%=site.title%>