Skip to content

Commit

Permalink
feat: interpolation ability implemented for translator
Browse files Browse the repository at this point in the history
  • Loading branch information
ayZagen committed May 4, 2020
1 parent ea3ff63 commit 9583231
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 11 deletions.
9 changes: 2 additions & 7 deletions src/ui/directives/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { DirectiveBinding, VNode, inject, ObjectDirective } from 'vue';
import { DirectiveBinding, VNode, ObjectDirective } from 'vue';

import { isPlainObject } from '../utils';

Expand All @@ -19,7 +19,7 @@ function parseValue(value: any): any {
let args: any = undefined
let choice: number | undefined = undefined

if (typeof value === 'string') {
if (typeof value === 'string' || !value) {
path = value
} else if (isPlainObject(value)) {
path = value.path
Expand Down Expand Up @@ -68,11 +68,6 @@ export const i18n: ObjectDirective = {
translate(el, binding, vnode)
},
unmounted: (el, binding, vnode, prevVNode) => {
const vm: any = vnode.appContext
if (!vm) {
console.warn('Vue instance does not exists in VNode context')
return
}

el._vt = undefined
delete el['_vt']
Expand Down
25 changes: 21 additions & 4 deletions src/ui/utils/translator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { parseArgs, propertyAccessor } from '.';
import { isObject, parseArgs, propertyAccessor } from '.';

export const translatorKey = Symbol('t')

Expand All @@ -9,7 +9,7 @@ export class Translator {
private selectedLocale: string
constructor(dictionary: any, fallbackLocale?: string) {
this.dictionary = dictionary;
this.fallBackLocale = fallbackLocale || 'en'
this.fallBackLocale = fallbackLocale || 'i18n'
}
set locale(locale: string){
this.selectedLocale = locale
Expand All @@ -21,8 +21,25 @@ export class Translator {
t(key: string, ...values: any){
const parsedArgs = parseArgs(values)
const locale = parsedArgs.locale || this.fallBackLocale
return propertyAccessor(this.dictionary[locale], key)
return this._interpolate(propertyAccessor(this.dictionary[locale], key)
|| propertyAccessor(this.dictionary[this.fallBackLocale], key)
|| key
|| key,
parsedArgs.params)
}
_interpolate(str: string, args: any){
if(!str){
return str
}
if(Array.isArray(args)){
args.forEach(arg => {
if(isObject(arg)){
Object.keys(arg).forEach(key => {
str = str.replace(`{${key}}`,
arg[key] === null || arg[key] === undefined ? '' : arg[key])
})
}
})
}
return str
}
}

0 comments on commit 9583231

Please sign in to comment.