Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌡️ feat: support i18n interpolate string #29

Merged
merged 1 commit into from
Aug 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/hooks/useLocale.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
import { useCallback } from 'react'
import { useRouter } from 'nextra/hooks'

import type { AllLocales, I18nLangKeys, LocaleKeys } from '@/i18n'
import { getNestedValue, i18nConfig } from '@/i18n'
import type { I18nLangKeys, LocaleKeys } from '@/i18n'
import { getNestedValue, i18nConfig, interpolateString } from '@/i18n'


export const useLocale = () => {
const { locale, defaultLocale } = useRouter()
const currentLocale = (locale || defaultLocale) as I18nLangKeys

const t = useCallback(
<K extends LocaleKeys>(key: K) => {
return getNestedValue(i18nConfig[currentLocale], key)
<K extends LocaleKeys>(key: K, withData: Record<string, any> = {}): string => {
const template = getNestedValue(i18nConfig[currentLocale], key)
if (typeof template === 'string') {
return interpolateString(template, withData)
}
return template || key
},
[currentLocale],
)
Expand Down
9 changes: 9 additions & 0 deletions src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,15 @@ export type NestedKeyOf<ObjectType extends object> = {
export type LocaleKeys = NestedKeyOf<AllLocales>


// 获取嵌套值
export function getNestedValue(obj: Record<string, any>, path: string): any {
return path.split('.').reduce((acc, key) => acc && acc[key], obj)
}

// 插入值表达式
export function interpolateString(template: string, context: Record<string, any>): string {
return template.replace(/\{\{(\w+(\.\w+)*)\}\}/g, (_, path) => {
const value = getNestedValue(context, path)
return value !== undefined ? value : `{{${path}}}`
})
}