NodeJS (Express 4) + i18n + 下划线:模板中的翻译问题

NodeJS (Express 4) + i18n + underscore: issue with translations in templates

本文关键字:问题 翻译 下划线 Express i18n NodeJS      更新时间:2023-09-26

使用: NodeJS (Express 4) + i18n + underscore.

我想在 NodeJS 中绑定和翻译一个下划线模板(Express 4)。

  • 绑定工作正常。
  • 翻译在模板之外工作正常。

但是我对模板内的翻译有问题:下划线不理解语法 <%= __('翻译键') %>: [ReferenceError: __ is not defined]

这是我的 NodeJS 代码:

var express = require('express'),
app     = express(),
cons    = require('consolidate'),
i18n    = require('i18n');
_       = require('underscore'),
// setup i18n
app.use(i18n.init);
i18n.configure({
    locales: ['en', 'fr'],
    directory:'./app/locales',
    defaultLocale: 'en'
});
// setup hbs
app.engine('html',cons.underscore);
app.set('views', './app/views');
app.set('view engine', 'html');
// translation test ok
console.log('Translation test: ' + i18n.__('hello'));
// rendering template generates error
app.render('test.html', {hello: 'Welcome !'}, function(err, html){
    if(err){
        console.log(err);
    } else {
        console.log(html);
    }
});

这是我的未评分模板"测试.html":

<h1><%= hello %></h1>
<p><%= __('hello') %></p>

以及英语 'en.json' 的 JSON i18n 文件:

{
    "hello": "hello my friend"
}  

我认为您缺少注册公共助手以获取视图。尝试在您的 NodeJS 应用程序中定义:

var hbs = require('hbs');
hbs.registerHelper('__', function () {
   return i18n.__.apply(this, arguments);
});

然后在您的模板中:

<p>{{{__ 'hello'}}}</p>