带有电子邮件模板的i18n模块

时间:2016-04-19 17:50:07

标签: node.js email internationalization nodemailer email-templates

我已设置nodemailer以使用email-templates模块,使用ejs作为渲染引擎。

到目前为止它按预期工作,但是,与我的应用程序的其他部分一样,我还想使用i18n模块将我的邮件文本翻译成与应用程序的渲染视图相同的方式。< / p>

不幸的是,它不起作用。这就是我尝试做的事情:

示例html.ejs:

<h1><%= __('Hi') %>, <%= user.name %>!</h1>

路线中的节点代码:

    // requires at the top
    var i18n = require('i18n');

    // (.....)

    // use template based sender to send a message
    sendMailTemplate({
        to: user.email,
        // EmailTemplate renders html and text but no subject so we need to
        // set it manually either here or in the defaults section of templateSender()
        subject: i18n.__('translatable subject')
    }, {
        user: user,
        __: i18n.__
    }, function(err, info){
        if(err){
           console.log('Error');
           console.log(err);
        }else{
            console.log('email sent');
            req.flash('info', i18n.__('mail sent to %s', user.email));
            done(err, 'done');                
        }
    });
    // other stuff...

只是一些事情:

  • 在我的邮件输出中,没有任何东西 - 字符串只是没有翻译。
  • 我相信简单地将i18n的{​​{1}}函数传递到渲染引擎的对象应该足以让它__可用并按预期执行,但我'我不确定。对此有何想法?
  • 我没有ejs,因此在i18n.setLocale(这是我在收到的电子邮件中看到的语言)时,它应该默认为英语。这可能是它没有按预期翻译的原因吗?

欢迎任何想法!

1 个答案:

答案 0 :(得分:0)

好吧,事实证明我是对的。 i18n确实默认为英语。我想我应该在将它传递给模板引擎之前设置语言环境,然后才能工作。

我使用express.js的req.accceptsLanguages()方法获得了首选语言。这不是故障保护,因为没有办法确保这确实是用户的母语(尽管在大多数情况下应该是这样)。

此外,由于我在全球范围内使用i18n,这就是为什么它是默认为英语的原因。因此,我将它传递给模板引擎,然后按照here

的指示使用它
__({phrase: 'Hello', locale: 'fr'}); // Salut

所以,最后一点是这样的:

// requires at the top
var i18n = require('i18n');

// (.....)

// THIS IS NEW - it's from express.js
// returns a shorthand for the user's preferred locale: en, es, de, fr, pt, ...
var userLocale = req.acceptsLanguages()[1];

// use template based sender to send a message
sendMailTemplate({
    to: user.email,
    // EmailTemplate renders html and text but no subject so we need to
    // set it manually either here or in the defaults section of templateSender()
    subject: i18n.__({phrase: 'translatable subject', locale: userLocale}) // note the syntax here
}, {
    user: user,
    __: i18n.__,
    locale: userLocale      // THIS IS ALSO NEW
}, function(err, info){
    if(err){
       console.log('Error');
       console.log(err);
    }else{
        console.log('email sent');
        // also note the syntax here:
        req.flash('info', i18n.__({phrase: 'mail sent to %s', locale: userLocale}, user.email)); 
        done(err, 'done');                
    }
});
// other stuff...
相关问题