Merge pull request #72 from lcnvals/i18n_string_template

feat: 字符串模版支持key
This commit is contained in:
菲鸽 2024-04-25 16:26:43 +08:00 committed by GitHub
commit 8e2c77f290
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 29 additions and 1 deletions

View File

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

View File

@ -49,4 +49,26 @@ export function formatString(template: string, ...values: any) {
return value !== undefined ? value : match 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 export default i18n

View File

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

View File

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