在本地化 (localize) 文字讯息时,我们可能会遇到需要特别处理 HTML tag的情况,什麽意思呢?我们来看一下上图红框中的句子的 HTML 结构。
<p>
For a guide and recipes on how to configure / customize this project,
<br />
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">
vue-cli documentation
</a>
.
</p>
这显然已经不是可以简单用 Message Format Syntax 解决的问题,所以今天我们要来分享的就是可以帮我们达到这件事的 Component Interpolation 。
此篇的内容会需要具备前两篇 Vue i18n - Message Format Syntax 以及 Vue i18n - Pluralization 所介绍到的语法基础,所以如果还没看过的朋友可以先去看过再回来此篇做阅读。
遇到上面的这种情况,你可能会尝试这麽做
{
"term1": "For a guide and recipes on how to configure / customize this project,",
"term2": "checkout out the",
"term3": "vue-cli documentation",
"period": "."
}
<p>
{{ $t('term1') }}
<br />
{{ $t('term2') }}
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">
{{ $t('term3') }}
</a>
{{ $t('period') }}
</p>
可惜的是这样只在英文语系行得通,原因是每个语言的文法其实差异很大,所以同样的一段句子在不同语言可能排列组合都不太一样,没办法都透过这样的方式去拼凑。
所以 Vue i18n 提供了 Translation 元件 (i18n-t) 来帮助我们达到这件事。
{
"intro": "For a guide and recipes on how to configure / customize this project, {0} checkout out the {1}.",
"vueCliDoc": "vue-cli documentation"
}
<i18n-t keypath="intro" tag="p">
<br/>
<a href="https://cli.vuejs.org" target="_blank">{{ $t("vueCliDoc") }}</a>
</i18n-t>
这样得到的结果就会是我们所期望的了。
<p>
For a guide and recipes on how to configure / customize this project,
<br />
check out the
<a href="https://cli.vuejs.org" target="_blank" rel="noopener">
vue-cli documentation
</a>
.
</p>
在上面的范例中,有两件事值得注意:
然而透过像是 list interpolation 完成插值,其实不太直观,还好我们可以透过 slots 做到类似 named interpolation 的方式!
{
"intro": "For a guide and recipes on how to configure / customize this project, {newline} checkout out the {doc}.",
"vueCliDoc": "vue-cli documentation"
}
<i18n-t keypath="intro" tag="p">
<template #newline>
<br />
</template>
<template #doc>
<a href="https://cli.vuejs.org" target="_blank">
{{ $t("vueCliDoc") }}
</a>
</template>
</i18n-t>
多元化的字词也有可能会需要使用到 Component interpolation,尤其是想要特别强调数量时可能需要有不一样的 CSS 效果,例如:
<p>
<strong>2</strong>
cars
</p>
所以我们可以在 i18n-t 组件透过 plural 属性来完成多元化。
"apple": "no apples | one apple | {count} apples"
<i18n-t keypath="apple" tag="p" :plural="count">
<template #count>
<strong>{{ count }}</strong>
</template>
</i18n-t>
export default {
// ...
setup () {
return {
count: 2
}
}
}
</script>
今天的分享就到这边,如果大家对我分享的内容有兴趣欢迎点击追踪 & 订阅系列文章,如果对内容有任何疑问,或是文章内容有错误,都非常欢迎留言讨论或指教的!
明天要来分享的是 Vue i18n 主题的第五篇 Number Formatting,那我们明天见!
>>: State 和生命周期(下) 正确的使用 State (Day6)
简报 ≠ PowerPoint 关於 Presentation program,其实还有其他的玩法~...
以昨天的例子而言,我们的 input 有 [Invalid / Valid]、[Disabled /...
基本上 每个网页的开头 都有个App Bar 用来登入登出 提示 搜索等等 以IT帮而言 虽然没有置...
对於其他人没什麽用的我的 git cheatsheet。 感觉还是要有情境呢.. git log ...
程序设计中资料结构与演算法是非常重要的两大项目,彼此之间都会影响程序的运作。 资料结构 电脑在储存资...