# gt: General Translation CLI tool: 键级元数据 URL: https://generaltranslation.com/zh/docs/cli/reference/keyed-metadata.mdx --- title: 键级元数据 description: 为 General Translation 的 JSON 和 YAML 文件附加针对各个键的翻译说明。键级元数据的 API 参考。 --- 你需要提供一个配套元数据文件,其键结构与源文件保持一致,并在每个叶子节点处包含一个元数据对象。每个对象都包含用于翻译该键的说明。 CLI 会自动检测配套元数据文件,依据源结构对其进行验证,并将其发送到翻译引擎。 ## 字段 [#fields] | 字段 | 描述 | 类型 | 可选 | 默认值 | | ---------------------------- | ------------------ | -------- | -- | --- | | [`context`](#context) | 特定 `string` 的翻译说明。 | `string` | 是 | — | | [`maxChars`](#max-chars) | 翻译结果的最大字符数。 | `number` | 是 | — | | [`sourceCode`](#source-code) | 以文件路径为键的周边源代码上下文。 | `object` | 是 | — | ## 文件结构 [#structure] 配套的元数据文件必须与源文件位于同一目录,遵循 `{name}.metadata.{ext}` 的命名约定,并在每个叶子节点处使用元数据对象,使其键结构与源文件保持一致。 ```text translations.json # 源字符串 translations.metadata.json # 各键的元数据 ``` 只需为需要说明的键提供条目。没有条目的键会照常翻译。 ```json title="translations.json" { "nav": { "home": "Home", "bank": "Bank", "save": "Save" } } ``` ```json title="translations.metadata.json" { "nav": { "bank": { "context": "河岸——河流的岸边。不是金融机构。" }, "save": { "context": "体育术语——守门员扑救阻止进球。不是保存数据。", "maxChars": 12 } } } ``` ## `context` [#context] **类型** `string` · **可选** · **默认值** — 应用于特定字符串的翻译说明。使用它来消除一词多义带来的歧义、指定领域术语,或说明期望表达的含义。 ```json { "bank": { "context": "Riverbank. The side of a river where land meets water, NOT a financial institution." } } ``` ## `maxChars` [#max-chars] **类型** `number` · **可选** · **默认值** — 对译文输出施加的最大字符限制。引擎会使用更短的近义表达、缩写或更精简的措辞,以尽量控制在该限制内。这是尽力而为的机制:如果源内容无法满足该限制,则会返回完整译文。 ```json { "save": { "maxChars": 10 } } ``` ## `sourceCode` [#source-code] **类型** `object` · **可选** · **默认值** — 字符串的周边源代码上下文,以文件路径为键。每个条目包含 `before` (目标行上方的源代码行) 、`target` (包含该字符串的那一行) 和 `after` (目标行下方的源代码行) 。如果同一个字符串在不同位置出现,则同一文件支持多个条目。 ```json { "new_lead": { "sourceCode": { "components/Dashboard.tsx": [ { "before": "function NotificationBanner({ type }) {\n const gt = useGT();", "target": " const msg = gt('You have a new lead!');", "after": " return {msg};\n}" } ] } } } ``` ### 综合示例 单个键包含全部三个字段: ```json { "save_button": { "context": "Sports term. A goalkeeper's save — preventing a goal from being scored. NOT saving data.", "maxChars": 12, "sourceCode": { "components/MatchStats.tsx": [ { "before": "const stats = useMatchStats();\nconst gt = useGT();", "target": "const label = gt('Save');", "after": "return }>{label}: {stats.saves};" } ] } } } ``` ## YAML [#yaml] 对于 `.metadata.yaml` 或 `.metadata.yml` 配套文件,元数据的处理方式也相同。 ```yaml title="translations.metadata.yaml" ui: buttons: save: context: "体育术语。守门员的扑救,而非保存数据。" maxChars: 12 labels: date: context: "椰枣树的可食用果实。而非日历日期。" ``` ## 验证 [#validation] CLI 会根据源结构验证元数据文件;如果某个元数据键在源中不存在、值类型与源不一致 (原始类型与对象、数组与对象) 、根类型不一致,或文件无法解析,则会报错并退出。 ## schema 与匹配 [#schema] 键级元数据可与 JSON schema (`include` 和 `composite`) 以及 YAML schema (`include`) 配合使用;元数据会经过同一个 schema 流水线进行转换,因此在翻译时,键路径能够保持一致。伴随文件会与其源文件进行匹配,不会单独翻译——如果 `.metadata.json` 文件没有匹配的源文件,就会被视为普通文件。仅更改元数据不会触发重新翻译;源内容也必须发生变化。