feat: 字符串模版支持key

This commit is contained in:
isaaczhao 2024-04-25 16:18:14 +08:00
parent 9f14ec7783
commit 155c2588f7
4 changed files with 29 additions and 1 deletions

View File

@ -1,5 +1,6 @@
{
"weight": "{heavy}KG",
"weight2": "{0}KG",
"introduction": "I am {name},height:{detail.height},weight:{detail.weight}",
"app.name": "En Title"
}

View File

@ -49,4 +49,26 @@ export function formatString(template: string, ...values: any) {
return value !== undefined ? value : match
})
}
/**
* formatStr('我是{name},身高{detail.height},体重{detail.weight}',{name:'张三',detail:{height:178,weight:'75kg'}})
*
* @param template
* @param data
* @returns
*/
export function formatStr(template, data) {
const match = /\{(.*?)\}/g.exec(template)
if (match) {
const variableList = match[0].replace('{', '').replace('}', '').split('.')
let result = data
for (let i = 0; i < variableList.length; i++) {
result = result[variableList[i]] || ''
}
return formatStr(template.replace(match[0], result), data)
} else {
return template
}
}
export default i18n

View File

@ -1,5 +1,6 @@
{
"app.name": "中文标题",
"weight": "{heavy}公斤",
"introduction": "我是 {name},身高:{detail.height},体重:{detail.weight}",
"weight2": "{0}公斤"
}

View File

@ -17,6 +17,9 @@
<view class="m-4">{{ $t('app.name') }}</view>
<view class="m-4">{{ $t('weight', { heavy: 100 }) }}</view>
<view class="m-4">{{ formatString(translate('weight2'), 100) }}</view>
<view class="m-4">
{{ formatStr(translate('introduction'), user) }}
</view>
<view class="text-green-500 mt-12">切换语言</view>
<view class="uni-list">
@ -36,10 +39,11 @@
</template>
<script lang="ts" setup>
import i18n, { formatString, translate } from '@/locale/index'
import i18n, { formatStr, formatString, translate } from '@/locale/index'
import { testI18n } from '@/utils/i18n'
const current = ref(uni.getLocale())
const user = { name: '张三', detail: { height: 178, weight: '75kg' } }
const languages = [
{
value: 'zh-Hans',