使用场景
假设你有一个条目列表,其内容因语言区域而异。例如,在一个功能列表中,不同语言可能包含不同的条目:
// 想要渲染出类似这样的效果
{features.map((feature) => (
<li>{feature}</li>
))}
比如英文版可能有 3 项功能,德文版可能有 4 项。你需要一种方式,以数组的形式存储和读取这些内容。
解决方案
在消息文件中将数组存储为 JSON 字符串,并在运行时用 JSON.parse() 解析:
// messages/en.json
{
"features": "[\"Fast\", \"Secure\", \"Easy to use\"]"
}
// messages/de.json
{
"features": "[\"Schnell\", \"Sicher\", \"Einfach\", \"Zuverlässig\"]"
}
import { m } from "./paraglide/messages.js";
const features: string[] = JSON.parse(m.features());
// en -> ["Fast", "Secure", "Easy to use"]
// de -> ["Schnell", "Sicher", "Einfach", "Zuverlässig"]
自花括号转义更新起,inlang-message-format 插件已支持对象。字面量 { 和 } 需转义为 \{ 和 \},反斜杠需转义为 \\。由于这是 JSON 格式,反斜杠必须双重转义。
{
"pricing": "\\{\"basic\": \"$9/mo\", \"pro\": \"$29/mo\"\\}"
}
const pricing = JSON.parse(m.pricing());
// -> { basic: "$9/mo", pro: "$29/mo" }
如果需要一种更便于译者编辑的格式,可以改为将对象编码为条目数组:
{
"pricing_entries": "[[\"basic\", \"$9/mo\"], [\"pro\", \"$29/mo\"]]"
}
const pricing = Object.fromEntries(
JSON.parse(m.pricing_entries()) as Array<[string, string]>
);
// -> { basic: "$9/mo", pro: "$29/mo" }
这样翻译值仍是纯文本,但也意味着 JSON 必须合法 (使用双引号,并按需转义) ,而且不能在 JSON 块中使用插值等消息格式特性。
[!NOTE] 如果数组项中需要插值,请改用多个独立的消息键:
// messages/en.json { "step_0": "Welcome, {name}!", "step_1": "You have {count} items in your cart", "step_2": "Proceed to checkout" }const steps = [ m.step_0({ name: "Alex" }), m.step_1({ count: 3 }), m.step_2(), ];
与 i18next 对比
i18next 提供了 returnObjects 选项,可直接返回数组:
// i18next
t('features', { returnObjects: true })
Paraglide 则改用 JSON.parse():
// Paraglide
JSON.parse(m.features())
为什么 Paraglide 不提供 returnObjects
i18next 的 returnObjects 会把翻译文件中的数组当作 JavaScript 代码处理,这会给译者带来麻烦。
Crowdin、Phrase 和 Lokalise 等翻译工具要求的是简单的键值对字符串:
┌─────────────────┬─────────────────────┐
│ Key │ Value │
├─────────────────┼─────────────────────┤
│ greeting │ Hello world │
│ farewell │ Goodbye │
└─────────────────┴─────────────────────┘
使用 returnObjects 时,译者看到的却是 JavaScript 语法:
┌─────────────────┬─────────────────────────────────────┐
│ Key │ Value │
├─────────────────┼─────────────────────────────────────┤
│ features │ ["Fast", "Secure", "Easy to use"] │
└─────────────────┴─────────────────────────────────────┘
译者必须原样保留 ["、"、, 和 "]。稍有差错,应用就会出问题:
// 你的代码
const features = t('features', { returnObjects: true })
features.map((f) => <li>{f}</li>)
// 译者不小心删掉了一个引号
- ["Fast", "Secure", "Easy to use"]
+ ["Schnell", "Sicher, "Einfach"]
// 运行时崩溃 - 语法无效导致 features 为 undefined
TypeError: Cannot read properties of undefined (reading 'map')
Paraglide 的 JSON.parse() 方案同样可能出现这个问题——译者仍然可能破坏 JSON 语法。区别在于,Paraglide 并没有把这种能力内置到 API 中。使用 JSON.parse() 是一个有意为之的“逃生舱”,用不用由你 (开发者) 自己决定。这是你主动选择承担的风险,而不是库默认提供、还得由库作者来维护的功能。
