kazupon / vue-i18n

:globe_with_meridians: Internationalization plugin for Vue.js
https://kazupon.github.io/vue-i18n/
MIT License
7.27k stars 860 forks source link

Nested variables #584

Open notiv-nt opened 5 years ago

notiv-nt commented 5 years ago

vue@2.6.8, vue-i18n@8.11.2

Reproduction Link

http://jsfiddle.net/psqw6gv9/

What is Expected?

messages: {
  en: {
    'hello': '{id} {data.name}'
  }
}

should work

What is actually happening?

data.name not working

Solution ?

function getDeep(obj, path) {
  var props = (path || '').split('.');
  let current = obj;

  for (var i of props) {
    if (!current || !current.hasOwnProperty(i)) {
      return null;
    }

    current = current[i];
  }

  return current;
}
compiled.push(getDeep(values, token.value));

https://github.com/kazupon/vue-i18n/blob/d28e3b25d9bd9eac51fc3714a4a2940772d85c3d/src/format.js#L96-L98

grimzy commented 5 years ago

I've been flattening my parameters.

function flattenObjectParameters (obj, prefix = '') {
  return Object.keys(obj).reduce((params, key) => {
    const pre = prefix.length ? prefix + '.' : ''
    if (typeof obj[key] === 'object') {
      Object.assign(params, flattenObjectParameters(obj[key], pre + key))
    } else {
      params[pre + key] = obj[key]
    }
    return params
  }, {})

then

const params = {
  id: 3,
  data: {
    name: 'John',
  }
}

this.$t('hello', flattenObjectParameters(params))

I prefer your solution.

haan123 commented 2 years ago

any new news?