Search code examples
apostrophe-cms

Translating module options using apos.i18n?


I need an example of using the apostrophe-i18n module inside a custom widgets modules index.js file.

After searching through all of Apostrophes built-in modules, I realized that Apostrophe never uses i18n to translate javascript strings.

I tried the following (found in one module), but it says "self is not defined". How could I import the apostrophe-i18n module to translate my strings in index.js file?

module.exports = {
    extend: 'apostrophe-widgets',
    label: self.apos.i18n.__('Link Page'),
    addFields: {
        name: '_page',
        type: 'joinByOne',
        withType: 'apostrophe-page',
        label: self.apos.i18n.__('Page'),
        required: true,
        idField: 'pageId',
        filters: {
            projection: {
                title: 1,
                slug: 1
            }
        }
    }
};

Edit for reference:

i18n for module options is not required, since Apostrophe handles the locales for admin strings itself. After adding the widget to an apos.area or apos.singleton call, all strings appear inside locale/en.json, ready for translation (according to my observation).

It seems that apostrophe-i18n uses the browser language to determine the locale to use. This language has to be configured like this in app.js:

'apostrophe-i18n': {
  locales: ['en', 'de']
},

After that, all my translated strings inside locale/de.json were printed to the page.


The working code to use self inside modules (again, not needed for i18n):

module.exports = {

    construct: function(self, options) {
        options.label = self.apos.i18n.__('Link Page');
    },

    extend: 'apostrophe-widgets',
    addFields: [
        {
            name: '_page',
            type: 'joinByOne',
            withType: 'apostrophe-page',
            label: 'Page',
            required: true,
            idField: 'pageId',
            filters: {
                projection: {
                    title: 1,
                    slug: 1
                }
            }
        }
    ]
};

Solution

  • self doesn't exist outside the module's construct functions. Try instead

      construct: function(self, options) {
        options.label = self.apos.i18n.__('Link Page');
      }