Javascript 如何将i18next translate方法绑定到grunt contrib pug编译器

Javascript 如何将i18next translate方法绑定到grunt contrib pug编译器,javascript,express,gruntjs,internationalization,i18next,Javascript,Express,Gruntjs,Internationalization,I18next,我无法将i18next translate方法绑定到grunt-pug-i18n任务 我在一个网站上使用Node.js、Express.js和Pug,并使用i18next和i18next Express中间件进行国际化 因此,我在pug模板上使用此函数来查找翻译: =t('key') // or #{t('key')} 然后为了满足静态版本的需要,我在grunt任务中使用grunt-pug-i18n将网站编译成html。但基本用途需要我用如下名称空间替换模板中的t方法: #{$i18n.ke

我无法将i18next translate方法绑定到grunt-pug-i18n任务

我在一个网站上使用Node.js、Express.js和Pug,并使用i18next和i18next Express中间件进行国际化

因此,我在pug模板上使用此函数来查找翻译:

=t('key') // or #{t('key')} 
然后为了满足静态版本的需要,我在grunt任务中使用grunt-pug-i18n将网站编译成html。但基本用途需要我用如下名称空间替换模板中的t方法:

#{$i18n.key}
工作正常,但它破坏了动态版本

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

所以我试着让grunt-pug-i18n使用t('key')方法

使用此问题,我似乎可以将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
  };
}
试一试

请参阅此处的更多信息:

这样更好,因为它不再抛出错误消息。但它是用钥匙翻译的,而不是翻译。t('section.about.h2')给出的是section.about.h2而不是translationMh,这很奇怪。如果找不到给定键的翻译,则仅输出键是默认行为。我在一个使用jade模板的应用程序中也是这样做的。它在您的开发工具控制台中工作吗?起初也有类似的问题,但这是我的错,因为在翻译资源完全加载之前我正在接受翻译。你是对的,我在i18下一个实例化中用grunt.file.readJSON()替换了grunt.file.readJSON(),以获得翻译文件,它工作得非常好。
//supposedly bind the i18n.t method to the task
data: function() {
  return {
    t: i18n.t.bind(i18n)
  };
}