Vue I18n HTML-Interpolation

DarkZ

I have an array of all product features in json file with translations. Each locale string in en.json has some parts of the string highlighted somehow like bold or italic.

{
  "feature1": "bla bla bla <b>blabla</b> bla ... bla bla",
  "feature2": "<i>bla</i> bla <b>bla bla bla</b> bla ... <b>bla bla</b>"
}

I want to render them in a list but without using v-html because it's not recommended.

I tried component interpolation but it didn't help, I tried putting <b> and <i> inside a named slot but it didn't work because I tried to put opening and closing tags to different named slots and that led to a not valid HTML markup.

{
  "feature1": "bla bla bla {b}blabla{bclose} bla ... bla bla",
  "feature2": "bla bla {b}bla bla bla{bclose} bla ... {b}bla bla{bclose}"
}
<template>
  <i18n
   tag="li"
   v-for="feature in $i18n.messages.en.features"
   path="features"
  >
    <template v-slot:b>
      <b>
    </template>
    <template v-slot:bclose>
      </b>
    </template>
    ...
  </i18n>
</template>

the end result I'm trying to reach will look like this

  • bla bla bla blabla bla ... bla bla
  • bla bla bla bla bla bla ... bla bla

How could I achieve what I want to achieve but without using v-html?

deceze

The way you should do that is to keep all your HTML in your <template> block, and all your text in your i18n, and you'll have to tease apart those strings inside the HTML block into separate translations:

<i18n tag="li" path="features">
  <b>{{ $t('bla bla') }}</b>
</i18n>
{
  "features": "lorem ipsum {0} ...",
  "bla bla": "bar baz"
}

This results in:

<li>lorem ipsum <b>bar baz</b> ...</li>

It's a bit unfortunate that you need bla bla as separate word, but you need it as standalone block, you can't just transpose the HTML start and end tags into your string, as that would be the same as unsafe string interpolation.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related