节点JS + i18n +把手

时间:2019-03-13 15:18:51

标签: node.js internationalization handlebars.js express-handlebars

我正在尝试使用i18n在节点JS中创建一个多语言网站。快递和车把。

将我的代码共享到我尝试使用以下代码实现的底部。

https://gist.github.com/mashpie/5246334

app.js

const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const i18n = require('i18n');
const hbs = require('hbs');

const app = express();

i18n.configure({
    locales: ['en', 'ja'],
    defaultLocale :  ' ja ' ,
    cookie: 'locale',
    directory: "" + __dirname + "/locales"
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));

app.use(express.static(path.join(__dirname, 'public/static/')));
app.set('views', "" + __dirname + "/views");
app.set('view engine', 'hbs');
app.engine('hbs', hbs.__express);

app.use(cookieParser());

app.use(i18n.init);

hbs.registerHelper('__', function () {
    return i18n.__.apply(this, arguments);
});
hbs.registerHelper('__n', function () {
    return i18n.__n.apply(this, arguments);
});
const aboutRouter = require('./routes/about');

app.use('/about', aboutRouter);


    /* This section should always be in the end! */
    app.use((req, res) => {
        res.status(404).sendFile(path.resolve(__dirname, 'public', '404.html'));
});

    module.exports = app;

locales / en.json

{
  "text to test": "text to test on eng"
}

locales / ja.json

{
  "text to test": "text to test on jap"
}

about.hbs

<a href="/" class="btn btn-orange rounded mb-4">{{{__ "text to test"}}}</a>

routes / about.js

const express = require('express');
const router = express.Router();

router.get('/', function(req, res) {
    res.render('about');
});

module.exports = router;

现在,当我尝试运行代码时。没有错误。 about.hbs文件正在成功读取。但是“要测试的文本”被当作字符串使用,但是其值并未从JSON文件中解析。

现在我的疑问是:-

  • 应如何解析JSON文件?

  • 浏览器如何知道要调用哪个JSON?如何知道lang参数?

0 个答案:

没有答案
相关问题