我在项目中使用 Node 电子邮件模板,在某些用户事件中向用户发送自动电子邮件。
按照 github 页面中提到的示例,我可以使用 nodemailer 发送邮件程序,但我的问题是如何在这些电子邮件程序中支持多种语言。
一种可能的解决方案是拥有一个单独的 html 和 style.css 目录,但这样就会有太多目录,这并不是一个好的编程方法。
任何人都可以建议任何更好的方法来实现这一点吗?是否有一些现有的工具可以实现此目的?
https://github.com/angular-translate/angular-translate
P.S.: I have successfully handled translations in the angular UI using angular translate. How can I do same in express mailer templates in backend ?
谢谢
最佳答案
虽然这个答案使用了一些非常具体的技术,但它可能会让您走上正确的道路:
设置:
i18n
、 Jade
var jade = require('jade');
var i18n = require('i18n');
// [optional] cache read and compiled jade file
var templates = {}
function renderMailWithI18n (templatePath, lang) {
// use cached and compiled template or load and compile from file
templates[templatePath] = templates[templatePath] ||
jade.compileFile(path.join(__dirname, templatePath + '.jade'), { pretty: true});
// render template and pass i18n translate function
return templates[templatePath]({
__: function (translationId) {
return i18n.__({
phrase: translationId, locale: lang
});
}
})
}
<小时/>
var nodemailer = require('nodemailer');
var mailTransporter = nodemailer.createTransport(...);
mailTransporter.sendMail({
from: ...,
to: ...,
subject: i18n.__({ phrase: 'myMail.subject', locale: req.locale }),
renderMailWithI18n('myMail_text', req.locale).replace('<div>', '').replace('</div>', ''),
renderMailWithI18n('myMail_html', req.locale)
})
<小时/>
myMail_text.jade
div.
#{__('myMail.greeting')}
#{__('myMail.body')}
...
myMail_html.jade
span #{__('myMail.greeting')}
br
span #{__('myMail.body')}
...
<小时/>
translation_en.json(类似于 Angular 翻译)
{
"myMail": {
"subject": "English Subject",
"greeting": "English Greeting",
"body": English Body"
}
}
<小时/>
此外,不要忘记配置 i18n
以使用正确的翻译文件。
关于javascript - 如何在node.js中使用多语言邮件模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31081622/