如何在 运行 时在表单生成器中使用 I18n 和 Json 架构?

How to use I18n and Json Schema in Form-generator at run-time?

我有一个表单,它将由 formGenerator 基于从服务器获取的 json-schema 创建。我想翻译基于语言的值。我不知道我应该如何在 运行 时间使用 i18n 来处理它。

例如,服务器发送一个如下所示的 Json-schema,我们应该从中制作一个表单,例如:

{
  "instance": {
    "specification": {
      "label": "",
      "title": ""
    }
}

如果我们将它传递给我们的简单表单生成器,它只会生成两个空标签,如下所示:

我必须使用翻译文件(如下面的 en.json)来填充获取的 json-schema,然后将其传递给表单生成器。

  {
    "instance":{
        "specification":{
            "label":"this is label",
            "title":"this is title"
        }
    }
}

我知道如果这两个跨度在模板中我可以像下面那样使用 $t("instance.specification.label") 和 $t("instance.specification.label") 来使用 i18n 中的翻译文件使其工作:

<span>{{$t(instance.specification.label)}}</span>

<span>{{$t(instance.specification.title)}}</span>

但我想知道在这种动态 json 模式的情况下我应该怎么做?

似乎没有办法为此目的使用 i18n,所以我为这个用例创建了一个库,供任何和我有同样问题的人使用。这是图书馆:

https://www.npmjs.com/package/i18n-translator-for-json-templates

更新

要使用此包,您可以在模板文件中使用 mustache 模板(有关更多信息,请参阅 link),如下所示:

//template.json
{
      "platformType": "{{specification.platformType}}",
      "ownershipMode": "COBO",
      "version": 1,
      "description": "{{specification.description}}",
      "label": "{{specification.label}}"
}

而且你还得为它准备语言文件,例如:

//en_lang.json
 {"specification": {
        "platformType": "Android",
        "description": "Command Schema For 'Company Owned/Business Only'",
        "label": "COBO3"
      }
 }

最后你可以像下面的例子一样使用这个库:

import i18nTranslatorForJsonTemplates from "i18n-translator-for-json-templates";
const result = i18nTranslatorForJsonTemplates(en_lang, template);
console.log(JSON.stringify(result));
/*output
 {                                                                       
   "platformType": "Android",                                            
   "ownershipMode": "COBO",                                              
   "version": 1,                                                         
   "description": "Command Schema For 'Company Owned/Business Only'",    
   "label": "COBO3"                                                      
 }                                                                       
*/