🦉 Translations 🦉
如果配置得当,Owl 可以翻译所有已渲染的模板。 为此,需要提供一个 translate
函数,该函数接收以下两个参数:
- 一个字符串(要翻译的文本)
- 一个字符串(该文本的翻译上下文)
并返回一个翻译后的字符串。
例如:
js
const translations = {
fr: {
hello: "bonjour",
yes: "oui",
no: "non",
},
pt: {
hello: "bom dia",
yes: "sim",
no: "não",
},
};
const translateFn = (str, ctx) => translations[ctx]?.[str] || str;
const app = new App(Root, { templates, tranaslateFn });
// ...
有关如何配置 Owl 应用程序的更多信息,请参阅 应用配置页面。
一旦设置完成,所有渲染的模板都会通过 translateFn
进行翻译:
- 所有的文本节点会被替换为对应的翻译;
- 以下属性的值也会被翻译:
title
、placeholder
、label
和alt
; - 若某个节点不希望被翻译,可添加属性
t-translation="off"
; translate
函数的第二个参数是“上下文”,可用来提供更精确的翻译。 可以通过t-translation-context
属性在某个节点及其子节点上设置全局上下文;- 若某个特定属性(如
title
)需要不同上下文,则可通过t-translation-context-title
来单独指定。
例如,使用上面的 translateFn
,下面的模板:
xml
<div>hello</div>
<div t-translation="off">hello</div>
<div>Are you sure?</div>
<input placeholder="hello" other="yes"/>
将被渲染为:
xml
<div>bonjour</div>
<div>hello</div>
<div>Are you sure?</div>
<input placeholder="bonjour" other="yes"/>
再如,下面这个模板:
xml
<div t-translation-context="fr" title="hello">hello</div>
<div>Are you sure?</div>
<input t-translation-context-placeholder="pt" placeholder="hello" other="yes"/>
将被渲染为:
xml
<div title="bonjour">bonjour</div>
<div>Are you sure?</div>
<input placeholder="bom dia" other="yes"/>
注意:翻译是在模板编译阶段完成的,而不是在运行时进行的。
在某些场景中,你可能希望扩展可翻译属性的列表。 例如,如果你还想翻译 data-title
属性,可以通过 translatableAttributes
选项来定义额外的属性:
js
const app = new App(Root, {
templates,
tranaslateFn,
translatableAttributes: ["data-title"]
});
// ...
如果你希望移除默认的某个翻译属性,可以在属性名前添加 -
前缀:
js
const app = new App(Root, {
templates,
tranaslateFn,
translatableAttributes: ["data-title", "-title"],
});
// 在这个例子中,`data-title` 会被翻译,但 `title` 不会...