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>'}) }}
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:
path
attribute is the message key.place
attribute the placeholder.tag
attribute determines what type of element to render.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With