You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用apos.i18n翻译模块选项?求自定义Widget模块index.js使用示例及报错解决

Using apostrophe-i18n in Custom Widget index.js

Great question! The self is not defined error pops up because you’re trying to reference self directly in the top-level module export object—at that point, the widget module instance (which self represents) hasn’t been created yet by Apostrophe. Let’s break down the correct ways to translate strings in your widget’s backend configuration.

The construct method runs after your widget module is fully initialized, and it receives the module instance (self) as its first argument. This is the safest place to access self.apos.i18n and update your widget’s labels or options with translated text.

Here’s a complete working example:

module.exports = {
  extend: 'apostrophe-widgets',
  // Optional: Set a fallback label for cases where i18n isn’t ready yet
  label: 'Link Page',
  // Define your widget fields as usual
  addFields: [
    {
      name: 'pageLink',
      type: 'apostrophe-page',
      label: 'Page to Link' // We’ll translate this in the construct method
    }
  ],
  construct: function(self, options) {
    // Translate the widget’s main display label
    self.label = self.apos.i18n.__('Link Page');
    
    // Translate individual field labels in the schema
    self.schema.forEach(field => {
      if (field.name === 'pageLink') {
        field.label = self.apos.i18n.__('Target Page');
      }
    });
  }
};

Why Your Initial Approach Failed

When you write label: self.apos.i18n.__('Link Page') directly in the export object, Apostrophe hasn’t yet built the widget’s self instance. The export object is just a plain configuration blueprint at that stage—self only exists once Apostrophe processes and initializes the module.

Note on Apostrophe’s Built-in Modules

You’re correct that many built-in modules don’t translate backend strings directly in their index.js files. This is because:

  • Some static strings are intended to be translated on the frontend using Apostrophe’s client-side i18n tools.
  • Built-in modules often handle configuration in centralized workflows that avoid direct backend string translation.

Critical Pre-Requisite

Ensure you’ve properly configured the apostrophe-i18n module in your project’s app.js file, including setting up locales, default locale, and loading your translation files:

// In app.js
module.exports = {
  modules: {
    'apostrophe-i18n': {
      locales: ['en', 'de'],
      defaultLocale: 'en',
      directory: './locales'
    },
    // Your custom widget module
    'link-page-widget': {}
  }
};

内容的提问来源于stack exchange,提问作者Carsten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:12:07