Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue-i18n with HTML in named params

Tags:

vue.js

Suppose I have this message object:

{greetings: '{blah} is welcome'}

How can I inject HTML into that {blah}param?

I tried this, but it doesn't work:

{{ $t('greetings', {blah: '<foo>' + some_string + '</foo>'}) }}

like image 883
Alan Willms Avatar asked Jun 17 '16 02:06

Alan Willms


1 Answers

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>
like image 157
claviska Avatar answered Sep 20 '22 13:09

claviska