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

使用:NodeJS(Express 4)+ i18n +下划线。

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

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

但是我在模板内部有翻译问题:下划线不理解语法<%= __('translation key')%>: [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); } }); 

这是我的Undescore模板'test.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>