在Strapi本地插件中实现I18n本地化



我生成了一个本地插件并创建了一个文章模型,使用:

"pluginOptions": {
"i18n": {
"localized": true
}
},

inside hisarticle.settings。json文件,以便使用国际化(I18N)插件

使某些特定字段可翻译问题是,当运行命令时:

strapi develop——watch-admin

我最终有以下错误:

error模型出错了"Article"使用属性"localizations">

error TypeError: Cannot read property "uid"未定义的

删除pluginOptions"相反,给我的本地插件运行没有任何可翻译字段或articles__translations枢轴,应该生成到我的mysql数据库

"pluginOptions"是使用Content-Types Builder创建集合类型的模型设置中生成的非常相同的参数,但我不能让它在使用它用于本地插件时工作。

这是我的article.settings.json:

plugins/博客/模型/article.settings.json

{
"kind": "collectionType",
"collectionName": "articles",
"info": {
"name": "article"
},
"options": {
"draftAndPublish": false,
"timestamps": true,
"populateCreatorFields": true,
"increments": true,
"comment": ""
},
"pluginOptions": {
"i18n": {
"localized": true
}
},
"attributes": {
"title": {
"pluginOptions": {
"i18n": {
"localized": true
}
},
"type": "string",
"required": true,
"maxLength": 255,
"minLength": 3
},
"slug": {
"pluginOptions": {
"i18n": {
"localized": true
}
},
"type": "uid",
"targetField": "title",
"required": true
},
"featured": {
"pluginOptions": {
"i18n": {
"localized": false
}
},
"type": "boolean",
"default": false
},
"published_date": {
"pluginOptions": {
"i18n": {
"localized": false
}
},
"type": "datetime"
},
}
}

您可以使用content-type-builder插件作为解决方案。您不会在content-types文件夹下创建内容类型,而是以编程方式创建它。

作为一个非常简单的tag内容类型的例子:

{
"singularName": "tag",
"pluralName": "tags",
"displayName": "tag",
"description": "",
"draftAndPublish": false,
"pluginOptions": {
"i18n": {
"localized": true
}
},
"attributes": {
"label": {
"type": "string",
"pluginOptions": {
"i18n": {
"localized": true
}
},
"unique": true
}
}
}

注意,json的模式与plugin/server/content-types中的模式有点不同。

然后您可以像这样通过编程方式创建内容类型:

import { Strapi } from "@strapi/strapi";
import tag from "../content-types/tag.json";
import page from "../content-types/page.json";
export default ({ strapi }: { strapi: Strapi }) => ({
async createContentComponent() {
if (!tag) return null;
try {
const components: any = [];
const contentType = await strapi
.plugin("content-type-builder")
.services["content-types"].createContentType({
contentType: tag,
components,
});
return contentType;
} catch (e) {
console.log("error", e);
return null;
}
},
});

这就是管理员如何使用内容构建器UI创建内容类型的。

使用pluginOptions.i18n.localized: true

一种方法是这样做,例如,在插件的引导阶段。在这里,您还可以检查是否创建了内容。

作为奖励,您还可以创建否则无法工作的组件。

希望对你有帮助。

链接:在插件中以编程方式创建组件:https://github.com/strapi/strapi-plugin-seo/blob/main/server/services/seo.js

创建内容类型:https://github.com/strapi/strapi/blob/88caa92f878a068926255dd482180202f53fcdcc/packages/core/content-type-builder/server/controllers/content-types.js L48

编辑:您也可以保留原来的模式,并使用fn来转换它—至少现在只要其他方法不起作用:

https://github.com/strapi/strapi/blob/1eab2fb08c7a4d3d40a5a7ff3b2f137ce0afcf8a/packages/core/content-type-builder/server/services/content-types.js L37

最新更新