Sailsjs req.setLocale outside controller

假如想象 提交于 2019-12-24 14:31:32

问题


I want to set the locale to other language than the default one, in cronjob scheduler. https://github.com/ghaiklor/sails-hook-cron

The cronjob scheduler code looks like that:

// ['seconds', 'minutes', 'hours', 'dayOfMonth', 'month', 'dayOfWeek']
module.exports.cron = {
  job: {
    schedule: '0 0 12 * * *',
    onTick: function() {
      SomeService.sendSms()
    },
    timezone: 'Asia/Jerusalem'
  }
}

But I cant set the locale because its not a controller but a service and I don't have access to req.setLocale globally.


回答1:


This depends on which version of Sails you're using.

For Sails v0.12.x, the only way to specify a locale dynamically is by using a dictionary as the argument to sails.__:

sails.__({ phrase: 'Welcome', locale: 'fr' })

will give you Bienvenue with a default Sails app.

This syntax isn't available in Sails 1.0, but you can change the current locale with sails.hooks.i18n.setLocale():

var curLocale = sails.hooks.i18n.getLocale();
sails.hooks.i18n.setLocale('fr');
sails.__('Welcome');
sails.hooks.i18n.setLocale(curLocale);

will again give you Bienvenue with a default Sails app, while ensuring that the locale is set back to the default afterwards. This way you don't accidentally change the locale for all subsequent invocations of __.



来源:https://stackoverflow.com/questions/45532581/sailsjs-req-setlocale-outside-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!