I was having a problem with html and component interpolation. (there is a solution below :smile:)
My issue was with replace translation variables with vue components or html elements
For example
en.json
{
"message": "Hello {visitor}, Login {loginLink} or register {registerLink}"
}
using v-html was bad option because it wouldn't parse vue components and I can't use html interpolation
module.exports = {
data(){
return {
visitorName: "visitor"
};
},
computed: {
message(){
return this.$("message", {
visitor: this.visitorName,
loginLink: '<router-link to="/login">Login</router-link>',
registerLink: '<router-link to="/register">Register</router-link>',
})
}
}
};
div#message(v-html="message")
This would output
<div id="message">
Hello visitor, Login <router-link to="/login">Login</router-link> or <router-link to="/register">Register</router-link>
</div>
I solved it by using slots and make custom translation component
translation.js
const regex = /{\s*\w+\s*}/g;
module.exports = {
props: [
"path",
"translation"
],
render: function (createElement) {
let translation = this.path ? this.$t(this.path) : this.translation || "";
let nodes = translation.split(regex);
let index = -1, m;
while ((m = regex.exec(translation)) !== null) {
if (m.index === regex.lastIndex)
regex.lastIndex++;
index += 2;
let key = m[0].replace(/[{}]/g, "").trim();
nodes.splice(index, 0, this.$slots[key]);
}
return createElement("div", nodes);
},
};
usage
test.vue
<template lang="pug">
translation(:translation="$t('message')")
span(slot="visitor") {{visitorName}}
router-link(slot="loginLink", to="/login") Login
router-link(slot="registerLink", to="/register") Register
// or using path prob
// translation(path="message")
</template>
<script>
module.exports = {
data(){
return {
visitorName: "Visitor"
}
},
}
</script>
output
<div>
Hello visitor, Login <a href="/login">Login</a> or <a href="/register">Register</a>>
</div>
Maybe variables extracting isn't the same as the plugin
I think it would be a good idea if it was a built-in component in the plugin.
Thanks!
@kazupon is there an example or a doc about how to use the interpolation?
Most helpful comment
See (WIP):
https://github.com/kazupon/vue-i18n/blob/dev/gitbook/en/interpolation.md