admin管理员组文章数量:1023876
Consider a HTML snippet such as this containing a series of placeholders (contained within single curly braces).
<div>
{ user.name }
{ user.username }
{ user.address.line1 }
{ user.address.line2 }
</div>
and a JavaScript object that looks like this:
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
What's the best way to replace the placeholders with their equivalent variables? I appreciate this is a basic form of templating but i don't want a 3rd party dependency for handlebars or similar. I also don't want to add any specifics to the template other than the placeholders themselves. Changing the placeholder delimeter to something else would be fine if there was a specific need to do that such a clash with another library.
This is a snippet of JS from a larger file which we're using to parse the placeholders. It works fine but i'm not sure whether it's good practice, it's certainly not particularly elegant! It goes without saying we're wanting to do this without using eval()
as the source of the data is a 3rd party.
var template = $(self.options.templateId).html();
for (var k in user) {
if (!user.hasOwnProperty(k)) continue;
if(k == 'address'){
for (var k in user.address) {
if (!user.address.hasOwnProperty(k)) continue;
var needle = "{ user.address." + k + " }";
template = template.replace(needle, user.address[k]);
}
}else{
var needle = "{ user." + k + " }";
template = template.replace(needle, user[k]);
}
}
This is part of a jQuery plugin so any jQuery specific code is fine.
Thanks
Consider a HTML snippet such as this containing a series of placeholders (contained within single curly braces).
<div>
{ user.name }
{ user.username }
{ user.address.line1 }
{ user.address.line2 }
</div>
and a JavaScript object that looks like this:
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
What's the best way to replace the placeholders with their equivalent variables? I appreciate this is a basic form of templating but i don't want a 3rd party dependency for handlebars or similar. I also don't want to add any specifics to the template other than the placeholders themselves. Changing the placeholder delimeter to something else would be fine if there was a specific need to do that such a clash with another library.
This is a snippet of JS from a larger file which we're using to parse the placeholders. It works fine but i'm not sure whether it's good practice, it's certainly not particularly elegant! It goes without saying we're wanting to do this without using eval()
as the source of the data is a 3rd party.
var template = $(self.options.templateId).html();
for (var k in user) {
if (!user.hasOwnProperty(k)) continue;
if(k == 'address'){
for (var k in user.address) {
if (!user.address.hasOwnProperty(k)) continue;
var needle = "{ user.address." + k + " }";
template = template.replace(needle, user.address[k]);
}
}else{
var needle = "{ user." + k + " }";
template = template.replace(needle, user[k]);
}
}
This is part of a jQuery plugin so any jQuery specific code is fine.
Thanks
Share Improve this question edited Feb 7, 2014 at 15:10 robjmills asked Feb 5, 2014 at 10:06 robjmillsrobjmills 18.6k16 gold badges80 silver badges123 bronze badges 1- You could check what underscore.js does under the hood, because its templating system is the most minimal [yet functional] I've ever seen. – moonwave99 Commented Feb 5, 2014 at 10:59
4 Answers
Reset to default 3Have a day off and what do I do? code something like this.
Tried to implement the template processing from scratch. It should perfectly fit your needs:
No Library used except jquery for adding the piled template into DOM.
Feel free to use it. Any1 is wele to make this code better or smaller ;)
plunker
$(document).ready(function () {
var tmpl =
' <div>'+
' { user.name }'+
' { user.username }'+
' { user.address.line1 }'+
' { user.address.line2 }'+
'</div>';
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
function pileTmpl(templateStr, data) {
var tmpl = ''+templateStr;
var tokens = tmpl.match(/\{(.[^{]+)\}/ig);
for(var i=0; i<tokens.length; i++) {
var t = tokens[i].replace(/([{}\s]+)/ig, '');
if(t && t.length > 0) {
var propChain = t.split('.');
var val = data;
for(var p=0; p<propChain.length; p++) {
if(val && val.hasOwnProperty(propChain[p])) {
val = val[propChain[p]];
}
}
if(val.length > 0) {
tmpl = tmpl.replace(new RegExp('{[ ]*'+t+'[ ]*}', 'ig'), val);
}
}
}
return tmpl;
}
var piledTmpl = pileTmpl(tmpl, {user: user});
$('body').append(piledTmpl);
});
Output:
<div> Bob Foo bobfoo 10 Foo Street Footown></div>
If I had to do this, I have used AngularJS.
For data-binding to HTML you can use AngularJS.
For future: AngularJS use double brackets {{ }}, if you use single brackets critical, that you can change it in AngularJS script.
var sampleApp = angular.module('YourApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('{');
$interpolateProvider.endSymbol('}');
});
you should use some Id's or classes for exampel
<div id="box1">
<span class="name">{ user.name }</span>
<span class="username">{ user.username }</span>
<span class="line1">{ user.address.line1 }</span>
<span class="line2">{ user.address.line2 }</span>
</div>
So u can access the html with jquery easiely, like this:
$('#box1 .name').html(user.name);
or
$('#box1 .name').text(user.name);
one of these should worke fine
You better use the popular template plugin: http://skilldrick.co.uk/tmpl/#slide6
Instead of using custom code.
Consider a HTML snippet such as this containing a series of placeholders (contained within single curly braces).
<div>
{ user.name }
{ user.username }
{ user.address.line1 }
{ user.address.line2 }
</div>
and a JavaScript object that looks like this:
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
What's the best way to replace the placeholders with their equivalent variables? I appreciate this is a basic form of templating but i don't want a 3rd party dependency for handlebars or similar. I also don't want to add any specifics to the template other than the placeholders themselves. Changing the placeholder delimeter to something else would be fine if there was a specific need to do that such a clash with another library.
This is a snippet of JS from a larger file which we're using to parse the placeholders. It works fine but i'm not sure whether it's good practice, it's certainly not particularly elegant! It goes without saying we're wanting to do this without using eval()
as the source of the data is a 3rd party.
var template = $(self.options.templateId).html();
for (var k in user) {
if (!user.hasOwnProperty(k)) continue;
if(k == 'address'){
for (var k in user.address) {
if (!user.address.hasOwnProperty(k)) continue;
var needle = "{ user.address." + k + " }";
template = template.replace(needle, user.address[k]);
}
}else{
var needle = "{ user." + k + " }";
template = template.replace(needle, user[k]);
}
}
This is part of a jQuery plugin so any jQuery specific code is fine.
Thanks
Consider a HTML snippet such as this containing a series of placeholders (contained within single curly braces).
<div>
{ user.name }
{ user.username }
{ user.address.line1 }
{ user.address.line2 }
</div>
and a JavaScript object that looks like this:
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
What's the best way to replace the placeholders with their equivalent variables? I appreciate this is a basic form of templating but i don't want a 3rd party dependency for handlebars or similar. I also don't want to add any specifics to the template other than the placeholders themselves. Changing the placeholder delimeter to something else would be fine if there was a specific need to do that such a clash with another library.
This is a snippet of JS from a larger file which we're using to parse the placeholders. It works fine but i'm not sure whether it's good practice, it's certainly not particularly elegant! It goes without saying we're wanting to do this without using eval()
as the source of the data is a 3rd party.
var template = $(self.options.templateId).html();
for (var k in user) {
if (!user.hasOwnProperty(k)) continue;
if(k == 'address'){
for (var k in user.address) {
if (!user.address.hasOwnProperty(k)) continue;
var needle = "{ user.address." + k + " }";
template = template.replace(needle, user.address[k]);
}
}else{
var needle = "{ user." + k + " }";
template = template.replace(needle, user[k]);
}
}
This is part of a jQuery plugin so any jQuery specific code is fine.
Thanks
Share Improve this question edited Feb 7, 2014 at 15:10 robjmills asked Feb 5, 2014 at 10:06 robjmillsrobjmills 18.6k16 gold badges80 silver badges123 bronze badges 1- You could check what underscore.js does under the hood, because its templating system is the most minimal [yet functional] I've ever seen. – moonwave99 Commented Feb 5, 2014 at 10:59
4 Answers
Reset to default 3Have a day off and what do I do? code something like this.
Tried to implement the template processing from scratch. It should perfectly fit your needs:
No Library used except jquery for adding the piled template into DOM.
Feel free to use it. Any1 is wele to make this code better or smaller ;)
plunker
$(document).ready(function () {
var tmpl =
' <div>'+
' { user.name }'+
' { user.username }'+
' { user.address.line1 }'+
' { user.address.line2 }'+
'</div>';
var user = {
name: 'Bob Foo',
username: 'bobfoo',
address : {
line1: '10 Foo Street',
line2: 'Footown'
}
};
function pileTmpl(templateStr, data) {
var tmpl = ''+templateStr;
var tokens = tmpl.match(/\{(.[^{]+)\}/ig);
for(var i=0; i<tokens.length; i++) {
var t = tokens[i].replace(/([{}\s]+)/ig, '');
if(t && t.length > 0) {
var propChain = t.split('.');
var val = data;
for(var p=0; p<propChain.length; p++) {
if(val && val.hasOwnProperty(propChain[p])) {
val = val[propChain[p]];
}
}
if(val.length > 0) {
tmpl = tmpl.replace(new RegExp('{[ ]*'+t+'[ ]*}', 'ig'), val);
}
}
}
return tmpl;
}
var piledTmpl = pileTmpl(tmpl, {user: user});
$('body').append(piledTmpl);
});
Output:
<div> Bob Foo bobfoo 10 Foo Street Footown></div>
If I had to do this, I have used AngularJS.
For data-binding to HTML you can use AngularJS.
For future: AngularJS use double brackets {{ }}, if you use single brackets critical, that you can change it in AngularJS script.
var sampleApp = angular.module('YourApp', [], function($interpolateProvider) {
$interpolateProvider.startSymbol('{');
$interpolateProvider.endSymbol('}');
});
you should use some Id's or classes for exampel
<div id="box1">
<span class="name">{ user.name }</span>
<span class="username">{ user.username }</span>
<span class="line1">{ user.address.line1 }</span>
<span class="line2">{ user.address.line2 }</span>
</div>
So u can access the html with jquery easiely, like this:
$('#box1 .name').html(user.name);
or
$('#box1 .name').text(user.name);
one of these should worke fine
You better use the popular template plugin: http://skilldrick.co.uk/tmpl/#slide6
Instead of using custom code.
本文标签: javascriptReplacing placeholders within HTML snippetStack Overflow
版权声明:本文标题:javascript - Replacing placeholders within HTML snippet - Stack Overflow 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://it.en369.cn/questions/1745511686a2153854.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论