【问题标题】:How to bind i18next translate method to a grunt-contrib-pug compiler如何将 i18next translate 方法绑定到 grunt-contrib-pug 编译器
【发布时间】:2017-04-04 01:54:18
【问题描述】:

我无法将 i18next translate 方法绑定到 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 任务?

【问题讨论】:

    标签: javascript express gruntjs internationalization i18next


    【解决方案1】:

    代替

    //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

    【讨论】:

    • 这样更好,因为它不再抛出错误消息。但它用键而不是翻译来翻译。 t('section.about.h2') 给出 section.about.h2 而不是翻译
    • 嗯,这很奇怪。如果找不到给定键的翻译,则仅输出键是默认行为。我也在使用玉模板的应用程序中这样做。它在您的开发工具控制台中有效吗?一开始有类似的问题,但这是我的错,因为我在翻译资源完全加载之前访问翻译
    • 你说得对,我在 i18next 实例化中将 grunt.file.read() 替换为 grunt.file.readJSON() 以获得翻译文件,它工作得很好。
    猜你喜欢
    • 1970-01-01
    • 2014-02-25
    • 2013-07-22
    • 2015-01-02
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    相关资源
    最近更新 更多