KScript 文档
ZH

语言

翻译:@t()

将翻译放在脚本旁边的 locales 文件夹中(或放在站点文件夹中):locales/en.json、locales/fr.yaml,或者每个语言区域一个文件夹,例如 locales/de/shop.json,其键以 shop. 开头。

YAML
# locales/fr.yaml
hello: Bonjour, {name} !
cart:
  items:
    "=0": Votre panier est vide
    one: "{count} article"
    other: "{count} articles"
<locale set="fr" />
<echo>{ @t('hello', { name: $user.name }) }</echo> <!-- Bonjour, Ann ! -->
<echo>{ @t('cart.items', { count: $cart->count() }) }</echo> <!-- 3 articles -->
<echo>{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }</echo> <!-- 9,50 € 20 novembre 2026 -->
locale(set: 'fr')
echo "{ @t('hello', { name: $user.name }) }" // Bonjour, Ann !
echo "{ @t('cart.items', { count: $cart->count() }) }" // 3 articles
echo "{ @format_currency($total, 'EUR') } { @format_date(@today(), 'long') }" // 9,50 € 20 novembre 2026
  • 复数形式。使用 count 时,@t() 会依据该语言自身的规则选择 zero、one、two、few、many 或 other。这些是英语、法语、葡萄牙语、俄语、乌克兰语、波兰语、捷克语、阿拉伯语、希伯来语、爱尔兰语、威尔士语、日语、中文、韩语等语言的 CLDR 规则。精确形式(如 =0)优先。
  • 回退。若缺少某个翻译,会依次在 fr-CA、fr 以及默认语言区域(除非另行设置,为 en)中查找。若各处都找不到,则返回键本身,并在 i18n 类别下记录一次警告。
  • 区域设置来自 locale(set: fr),来自 locale(from: …)(与列表或 Accept-Language 请求头最匹配的可用项),来自 $config.i18n.locale,来自 KSCRIPT_LOCALE,或来自计算机的语言。@locale() 会提供它,@locales() 会列出存在文件的所有区域设置。设置区域设置的路由或中间件,会在其中选定其响应所用的 @view(),并优先于请求所要求的语言,因此站点可以让自己的 Cookie 优先于浏览器的设置。
  • 页面按以下顺序选择语言区域:路径前缀(当存在法语翻译时,/fr/about 会以法语提供 about.html)、?lang=fr、lang Cookie,最后是浏览器的 Accept-Language。@locale_path($request.path, 'de') 会给出指向同一页面德语版本的链接。默认语言区域没有前缀。
  • 格式化。这些会遵循当前语言区域,或遵循作为最后一个参数传入的语言区域:
    • @format_number(1234.5) 输出 1,234.5 或 1 234,5;
    • @format_percent(0.25);
    • @format_currency(9.5, 'GBP');
    • @format_date(date, 'short' | 'medium' | 'long' | 'full' | 'time' | 'datetime' | 'd MMMM yyyy');
    • @format_relative(date, from?) 输出 3 hours ago、in 2 days 或 just now,除非给出 from:,否则以当前时间为基准;
    • @format_duration(1h30m) 输出 1 hour 30 minutes;
    • @format_list(['tea', 'coffee', 'milk']) 输出 tea, coffee and milk,使用 style: 'or' 时输出 tea, coffee or milk;
    • @format_ordinal(23) 输出 23rd,法语中输出 23e;
    • @format_bytes($file.size) 输出 1.4 MB,使用 binary: true 时输出 1.3 MiB。
  • 设置:配置中的 i18n: { folder: lang, default: en-GB, locale: fr },或 translations(folder: lang, default: en-GB)。@has_t(key) 检查某个键是否有翻译,@plural(count) 则给出复数类别。

相对时间、时长、列表和序数的词语已为英语、法语、德语、西班牙语、意大利语、葡萄牙语和荷兰语内置。对于其他语言,或要修改这些词语,请在对应的翻译文件中添加这些键:time.second 至 time.year(带复数形式),以及 {count}、time.ago 和 time.in(配合 {time}、time.now、list.and、list.or),还有 ordinal(配合 {count}):

YAML
# locales/pl.yaml
time:
  hour: { one: "{count} godzina", few: "{count} godziny", many: "{count} godzin" }
  ago: "{time} temu"