Vue-i18n with HTML in named params

You'll have to show me what you're trying to do with that message as far as displaying it in HTML, however at first pass it seems like what you'd want

this.msg = '<foo>' + some_string + '</foo>';

Then, within your HTML where you want to display this msg, you'd say:

{{{ msg }}}

Notice the triple brackets, this means that it is interpreting msg as being raw HTML and not an escaped string... use this with caution. If msg is purely something set by the front-end then it is fine; just don't let the some_string be user inputted data.


For Vue 2.0, things have changed:

If your message object is:

{greetings: '<foo>{blah}</foo> is welcome'}

Then on template side, you should have the following:

<p v-html="$t('greetings', {blah: some_string})"></p>

Works as well with <div v-html="..."></div>, and certainly other tags. See https://github.com/kazupon/vue-i18n/issues/73


Be cautious of the [previously] accepted answer, as untrusted input will lead to XSS vulnerabilities. The correct way to do this is with component interpolation. It works a little bit like slots.

Here's a practical example that wraps a link around a user's name:

const messages = { 
  welcome: 'Welcome, {user}!' 
};
<i18n
  path="welcome"
  tag="p"
>
  <a place="user" :href="user.link">{{ user.name }}</a>
</i18n>

This will result in the following output:

<p>Welcome, <a href="/users/bob">Bob Marley</a>!</p>

To make it easier to understand, note that:

  • The path attribute is the message key.
  • The place attribute the placeholder.
  • The tag attribute determines what type of element to render.
  • For multiple placeholders, simply add more elements with the appropriate place attribute.

If you're curious about the <i18n> component, you don't have to explicitly enable it — it gets registered when you initialize vue-i18n.

Update: as of version 8.14, place is deprecated in favor of the new slots syntax. Here's an updated example for 8.14 and above:

<i18n path="welcome" tag="p">
  <template v-slot:user>
    <a :href="user.link">{{ user.name }}</a>
  </template>
</i18n>

Tags:

Vue.Js