如何使用apos.i18n翻译模块选项?求自定义Widget模块index.js使用示例及报错解决
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.
Method 1: Use the construct Function (Recommended)
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

