vue-i18n 翻译中 html 标签的最佳实践?

Tit*_*tan 5 localization vue.js vuejs2

我正在使用vue-i18n,我需要翻译一个中间带有锚标记的句子。显然我想将 html 特定标记保留在我的翻译之外,但如何最好地处理这个问题?

考虑以下示例:

This is a test sentence which cannot 
<a href="https://example.com" class="test-class test-another-class">be split</a> 
or it will not make sense
Run Code Online (Sandbox Code Playgroud)

我能想出的唯一解决方案是:

{
    "en": {
        "example": "This is a test sentence which cannot {linkOpen}be split{linkClose} or it will not make sense"
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在组件模板中

<p v-html="$t('example', { 
    'linkOpen': `<a href="https://example/com" class="test-class test-another-class">`,
    'linkClose: '</a>'
    }) 
"></p>
Run Code Online (Sandbox Code Playgroud)

然而并不完全优雅......

编辑:我已经测试过这个并且它实际上不起作用(不能将 html 放入参数中)所以现在我真的没有想法了!

euv*_*uvl 2

您可以为链接提出一些简单的标记并编写一个小型转换函数,例如:

//In this example links are structured as follows [[url | text]]

var text = `This is a test sentence which 
cannot [[https://example.com | be split]] or it will not make sense`

var linkExpr = /\[\[(.*?)\]\]/gi;
var linkValueExpr = /(\s+\|\s+)/;

var transformLinks = (string) => {
  return text.replace(linkExpr, (expr, value) => {
    var parts = value.split(linkValueExpr);
    var link = `<a href="${parts[0]}">${parts[2]}</a>`;

    return link;
  });
}

alert(transformLinks(text));
Run Code Online (Sandbox Code Playgroud)

JSFiddle: https: //jsfiddle.net/ru5smdy3/

它将vue-i18n看起来像这样(当然你可以简化):

<p v-html="transformLinks($t('example'))"></p>
Run Code Online (Sandbox Code Playgroud)