Vue-i18n: Suggesion: built-in translation component to support html interpolation using slots

Created on 17 Apr 2017  路  3Comments  路  Source: kazupon/vue-i18n

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!

Most helpful comment

All 3 comments

144 #120 #37 #58 #75

@kazupon is there an example or a doc about how to use the interpolation?

Was this page helpful?
0 / 5 - 0 ratings

Related issues

zhaohaodang picture zhaohaodang  路  4Comments

blak3r picture blak3r  路  4Comments

karol-f picture karol-f  路  3Comments

cslee picture cslee  路  5Comments

shaunnetherby picture shaunnetherby  路  5Comments