0

我想创建一个文本模板并在其中设置占位符并填充此占位符并在我的页面中使用它?像 ..

var temp = '<div class="persons">';
temp += '<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>';
temp += '<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>';
temp += '<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>';
temp += '</div>';

并用我的价值观改变[firstname],并在页面中显示?或任何其他想法?[lastname][tel]

4

4 回答 4

3

快速而肮脏的 JS 模板引擎:

// Create a matching object for each of your replacement
var matches = {
    "[firstname]": "fred",
    "[lastname]": "smith",
    "[tel]": "123456789"
}

// Loop through the keys of the object
Object.keys( matches ).forEach( function( key ) {
    // Replace every key with its value
    temp = temp.replace( key, matches[ key ] )
} )
于 2012-04-25T20:55:25.633 回答
2

你可以简单地替换它们。

temp.replace("[firstname]", "fred").replace("[lastname]", "smith").replace("[tel]", "123456789");

不确定您是否使用 jQuery 模板。

于 2012-04-25T20:50:08.350 回答
2

你试过.replace()吗?

http://jsfiddle.net/KL9kz/

于 2012-04-25T20:53:30.813 回答
1

试试这样的东西,非常基本

function replaceall(tpl, o, _p, p_) {
    var pre = _p || '%',
        post = p_ || '%',
       reg = new RegExp(pre + '([A-z0-9]*)' + post, 'g'),
        str;
    return tpl.replace(reg, function (str, $1) {
        return o[$1];
    });
};
var temp = '<div class="persons">'+
        '<p> <span class="firstname">First Name :</span> <span> [firstname]</span> </p>'+
        '<p> <span class="lastname">Last Name :</span> <span> [lastname]</span> </p>'+
        '<p> <span class="tel">Telephone :</span> <span> [tel]</span> </p>'+
    '</div>',
    data = {
        'firstname':'Fede',
        'lastname':'Ghe',
        'tel' : '+00 012 3456789' 
    };
alert(replaceall(temp, data, '\\\[', '\\\]'));

如果需要,可以避开占位符界限并调整内部正则表达式希望它有所帮助

于 2012-09-12T12:09:53.100 回答