Home > Enterprise >  vue-i18n how to set default variable for formatting?
vue-i18n how to set default variable for formatting?

Time:10-25

format

const messages = {
  en: {
    message: {
      hello: '{msg} world'
    }
  }
}

usage

<p>{{ $t('message.hello', { msg: 'hello' }) }}</p>
<!-- I don't want to input the second param {msg: 'hello'} -->

how can I set the default value for 'msg' and no need to input {msg: 'hello'} in every $t function?

CodePudding user response:

You can define two messages:

const messages = {
  en: {
    message: {
      world: '{msg} world',
      helloWorld: 'Hello world'
    }
  }
}

Usage:

<!-- Use the translation without format syntax -->
<p>{{ $t('message.helloWorld' }}</p>
<!-- result: <p>Hello world</p> -->

<!-- Input the second param when you need it -->
<p>{{ $t('message.world', { msg: 'Goodbye' }) }}</p>
<!-- result: <p>Goodbye world</p> -->

CodePudding user response:

You could create yourself a custom $t2 method (or alike), which supersets the basic $t with a default param injection.
Clearly not sure that it's worth the hassle since it will not benefit from i18n's devtools hints (which are quite handy for sure) and is not worth the "time gained".

I'd stick to regular approach and put the effort into writing that manually when needed. Or stick to a hardcoded approach if no variable is needed.

  • Related