0

I'm trying to put together a small demonstration that uses client-side templating for a short talk. My regexp dynamically gets created and aims to replace instances of itself within a string, but it's not working for some odd reason, I've console logged the vital parts, can anyone advise?

My HTML:

<script type="text/template" id="link">
  <a href="{href}">
    {title}
  </a>
</script>

And my JavaScript in a jsFiddle and below:

var linkTemplate = document.querySelector('#link').innerHTML.replace(/^\s+|\s+$/g, '');

var data = [{
"title": "Google",
"href": "//google.com"
},{
"title": "Yahoo",
"href": "//yahoo.com"
}];

for (var i = 0; i < data.length; i++) {
var obj = data[i];
for (key in obj) {
    if (obj.hasOwnProperty(key)) {
        var regexp = new RegExp('\{' + key + '\}', 'i');
        console.log(regexp);
        linkTemplate.replace(regexp, 'l');
        console.log(obj[key]);
    }
}
document.body.innerHTML += linkTemplate;
}

http://jsfiddle.net/K9z6C/

4

3 回答 3

1

如果我正确理解了您的查询,您需要进行以下更改:

linkTemplate = linkTemplate.replace(regexp, 'l');

原因 -.replace()返回一个新字符串,其中模式的部分或全部匹配被替换替换。

编辑:根据您在 MC ND 的答案中发布的示例小提琴进行了更新。更新后的代码如下:

for (var i = 0; i < data.length; i++) {
    var obj = data[i];
    link = linkTemplate; //set the temporary variable with the template script for every data item
    for (key in obj) {
        if (obj.hasOwnProperty(key)) {
            var regexp = new RegExp('\{' + key + '\}', 'g');
            link = link.replace(regexp, obj[key]); //replace the href and title based on data
        }
    }
    document.body.innerHTML += link + '<br/>'; //add the value from the temporary variable to document body.
}

演示小提琴

于 2013-10-20T14:13:23.870 回答
0

您还可以反转登录并匹配所有{...},然后尝试获取数据:

var str = 'hello {name}, you are {age} years old',
    tpl = function(str, data) {
        return str.replace(/\{(.*?)\}/g, function(_, a) { return data[a]; });
    };

tpl(str, {name: 'John', age: 47}); // Hello John, you are 47 years old
于 2013-10-20T14:14:25.530 回答
0

一旦您为第一组数据替换了 linkTemplate 中的内容,您就没有更多的占位符可以替换第二组数据。保存到临时刺痛以添加到结果中。

于 2013-10-20T14:15:59.067 回答