如何将 i18next 翻译方法绑定到 grunt-contrib-pug 编译器

How to bind i18next translate method to a grunt-contrib-pug compiler

我无法将 i18next 翻译方法绑定到 grunt-pug-i18n 任务。

我在带有 i18next 和 i18next-express-middleware 的网站上使用 Node.js、Express.js 和 Pug 进行国际化。

因此我在 pug 模板上使用此功能来查找翻译:

=t('key') // or #{t('key')} 

然后为了静态版本的需要,我在 grunt 任务中使用 grunt-pug-i18n 将网站编译成 html。但是基本用途需要我用这样的命名空间替换模板中的 t 方法:

#{$i18n.key}

工作正常,但它破坏了动态版本。

我需要一个解决方案,让动态世界和静态世界以相同的方式工作。

所以我试图让 grunt-pug-i18n 与 t('key') 方法一起工作。

使用这个问题 https://github.com/AdesisNetlife/grunt-pug-i18n/issues/21,看起来我可以将 i18n.t 方法绑定到 options.data 这样任务就可以理解模板中的 t 方法:

// instantiate i18next
var i18n = require('i18next');
i18n.init({
  lng: 'en',
  resources: {
    en: {
      translation: grunt.file.readJSON( webDir + 'locales/en/translation.json' )
    }
  }
});
console.log(i18n.t('key'));//works fine

...

// grunt task
pug: {
  compile: {
    options: {
      namespace   : 'JST',
      separator   : '\n\n',
      amd         : false,
      client      : false,
      pretty      : true,
      self        : false,
      debug       : false,
      compileDebug: true,
      //i18n specific options
      i18n: {
        locales: webDir + 'locales/en/translation.json'
      },
      //supposedly bind the i18n.t method to the task
      data: function() {
        return {
          t: i18n.t
        };
      }
    },
    files: [ {
      cwd: webDir + 'views',
      src: ['**/*.pug', '!**/_*.pug'],
      dest: webDir + 'static',
      expand: true,
      ext: '.htm'
    } ]
  }
}

看起来绑定已经完成,但我最终遇到了这个错误:

>> TypeError: website/views/_layout.pug:9
>>     7|     meta( name='description' content='' )
>>     8|     meta( name='author' content='' )
>>   > 9|     title=t('title')
>>     10|   
>> Cannot read property 'translator' of undefined

如何将 i18next 翻译方法绑定到 grunt-contrib-pug 任务?

而不是

//supposedly bind the i18n.t method to the task
data: function() {
  return {
    t: i18n.t
  };
}

尝试

//supposedly bind the i18n.t method to the task
data: function() {
  return {
    t: i18n.t.bind(i18n)
  };
}

在此处查看更多信息: https://github.com/i18next/i18next-express-middleware/blob/master/src/index.js#L33