2017-03-07 59 views
2

我使用的是vue-i18n,我需要在中間翻譯帶有錨標記的句子。很明顯,我想保留我的翻譯html特定的標記,但如何最好地處理這個?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中的參數),所以現在我真的沒有想法!

回答

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> 
0

您可以將HTML放入不屬於顯示的DOM部分的元素,然後提取其textContent。儘管如此,這可能不適用於你實際想要做的事情。我不知道。

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>