【问题标题】:NodeJS (Express 4) + i18n + underscore: issue with translations in templatesNodeJS (Express 4) + i18n + underscore:模板中的翻译问题
【发布时间】:2014-12-11 13:57:49
【问题描述】:

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

我想在 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);
    }
});

这是我的 Undescore 模板“test.html”:

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

还有英文“en.json”的 JSON i18n 文件:

{
    "hello": "hello my friend"
}  

【问题讨论】:

    标签: javascript node.js express internationalization underscore.js


    【解决方案1】:

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

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

    然后在你的模板中:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2013-06-08
      相关资源
      最近更新 更多