JavaScript的替换”的变量和QUOT;在HTML code快变量、rdquo、JavaScript、code

2023-09-13 05:19:24 作者:含着棒棒糖看男友调戏闺蜜

我建立一个多语言单页网站使用JavaScript和新的HTML 模板 -tag并想用自己的变量,例如 {{txt.welcome}}在HTML 应当由翻译来代替。

I'm building a multi-language single page website with javascript and the new html template-tag and would like to use own variables like {{txt.welcome}} in html which should be replaced by the translation.

HTML

<div class="container">
  <h2>{{heading.hello}}</h2>
  <p>{{txt.welcome}}<br /><img alt="{{image.description}}" src="" /></p>
</div>

使用Javascript:

Javascript:

var reg = new RegExp(/{{([a-z.]+)}}/g);
var result;
while(result = reg.exec(document.documentElement.innerHTML)) {
    document.documentElement.innerHTML = document.documentElement.innerHTML.replace(result[0], translations[result[1]]);
}

据搜寻SEARCH_TERM_EXAMPLES在整个文档中的变量,并使用定义的文本取代他们,但有许多变数性能变得非常糟糕。

It searchs for the variables in the whole document and replace them with the defined text, but with many variables the performance becomes really bad.

这将是一个更快的解决方案比在整个文档的HTML与正则表达式循环?

What would be a faster solution than looping with regex over the whole document's html?

如何做到这一点其他图书馆像AngularJS与 {{'富'|翻译}}

How do it other libraries like AngularJS with {{ 'FOO' | translate }}?

推荐答案

最大的问题,我认为,是你不只是运行一个正则表达式,也运行替代在整个HTML 多次。而你实际的HTML DOM多次设置,而不是操纵一个字符串,直到你得到的结果,然后设置HTML一次。我会强烈建议使用类似Handlebars.js库,但如果你想自己做,一个非常快速的实现会是这样的:

The biggest issue, I think, is that you are not just running a regex, but also running a replace over the entire HTML multiple times. And you are setting the actual DOM HTML multiple times rather than manipulating a string until you get the result, and then setting the HTML once. I would strongly recommend using a library like Handlebars.js, but if you want to do it yourself, a very quick implementation would be something like:

var translations = { 
    heading: { 
        hello: "hello" 
    }, 
    txt: { 
        welcome: "welcome" 
    }, 
    image: { 
        description: "this is a test" 
    }
};

function get(obj, desc) {
    var arr = desc.split(".");
    while(arr.length && (obj = obj[arr.shift()]));
    return obj;
}

function replaceTokens(HTML) {
    return HTML.split('{{').map(function(i) { 
        var symbol = i.substring(0, i.indexOf('}}')).trim(); 
        return i.replace(symbol + '}}', get(translations, symbol)); 
    }).join('');
}