我正在使用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
我能想出的唯一解决方案是:
{
"en": {
"example": "This is a test sentence which cannot {linkOpen}be split{linkClose} or it will not make sense"
}
}
然后在组件模板中
<p v-html="$t('example', {
'linkOpen': `<a href="https://example/com" class="test-class test-another-class">`,
'linkClose: '</a>'
})
"></p>
然而不是很优雅......
编辑:我已经测试了这个并且它实际上没有用(不能把html放在params中)所以现在我真的没有想法了!
答案 0 :(得分:0)
您可以为链接提供一些简单的标记并编写一个小的转换函数,例如:
//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));
JSFiddle:https://jsfiddle.net/ru5smdy3/
使用vue-i18n
它看起来像这样(当然你可以简化):
<p v-html="transformLinks($t('example'))"></p>
答案 1 :(得分:0)
您可以将HTML放入不属于显示的DOM的元素中,然后提取其new Vue({
el: '#app',
data: {
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`,
utilityEl: document.createElement('div')
},
methods: {
htmlToText: function (html) {
this.utilityEl.innerHTML = html;
return this.utilityEl.textContent;
}
}
});
。但是,这可能不适用于您实际尝试做的事情。我不能告诉你。
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.2.1/vue.js"></script>
<div id="app">
<p v-html="html"></p>
<p>{{htmlToText(html)}}</p>
</div>
&#13;
{{1}}&#13;