kazupon / vue-i18n

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

Allow use of modifiers via `$t`, `$tc`, etc #866

Open IlCallo opened 4 years ago

IlCallo commented 4 years ago

Hi guys, I checked the docs but I cannot find a way to use modifiers directly via $t (and similar methods). I also checked other issues on the repo and found no feature request about this particular use case, but some related to a better integration of modifiers (https://github.com/kazupon/vue-i18n/issues/734, https://github.com/kazupon/vue-i18n/issues/748).

Seems like the only way is to use linked messages, but this pretty much duplicates my translations (although this could be automatized, being a JS object).

The specific use case is to provide expanded textual representation of some enum values. Those values are always the same, but their casing can change if they are at the beginning of the text node or after a label.

Current:

export default {
  myEnumValues: {
    option1: 'value1',
    option2: 'value2',
    option3: 'value3',
    option4: 'value4',
    option5: 'value5',
  },
  specificPageName: {
    myEnumValues: {
      option1: '@.capitalize:myEnumValues.option1',
      option2: '@.capitalize:myEnumValues.option2',
      option3: '@.capitalize:myEnumValues.option3',
      option4: '@.capitalize:myEnumValues.option4',
      option5: '@.capitalize:myEnumValues.option5',
    },
  }
}

$t('myEnumValues.option1');
$t('specificPageName.myEnumValues.option1');
// OR use an external capitalize() function
`capitalize($t('myEnumValues.option1'))`;

Proposed:

export default {
  myEnumValues: {
    option1: 'value1',
    option2: 'value2',
    option3: 'value3',
    option4: 'value4',
    option5: 'value5',
  },
}

$t('myEnumValues.option1');
$t('@.capitalize:myEnumValues.option1');

What do you think? Can this be useful to others too?

IlCallo commented 4 years ago

Example of automatization (using lodash.mapValues).

import { mapValues } from 'lodash-es';

const enums = {
  myEnumValues: {
    option1: 'value1',
    option2: 'value2',
    option3: 'value3',
    option4: 'value4',
    option5: 'value5',
  },
};

function capitalizeEnums() {
  return mapValues(enums, (enumObject, enumKey) =>
    mapValues(
      enumObject,
      (_, propertyKey) => `@.capitalize:${enumKey}.${propertyKey}`
    )
  );
}

export default {
  ...enums,
  specificPageName: {
    ...capitalizeEnums(),
  }
}

Even if this can help, it is an overkill in cases when you have to reference only some of the enum values: those middle cases where you need enough to become a problem to rewrite manually, but not all of them