A bit of templating
Not so long ago, from a lecture by Douglas Crockford, I learned about a very interesting technique of "template" in JavaScript. The main goal of the technique is that we get from the JSON server and then somehow form HTML from this. In many situations, this process leaves much to be desired because HTML is generated either by concatenating strings or using a series of createElement, appendChild, etc. Perhaps many already know about this solution, but for those who did not know, I hope it will be useful.
And so, you need from such data:
get this html:
Somehow scary. Options ??
Add the supplant method from Douglas Crockford to the String prototype:
The essence of the method is to go over the properties of the object received in the parameters, which were in the line and were enclosed in curly braces and replace the property names with their values. All this is similar to the Ruby # #} construct, which allows variable values to be inserted into a string without concatenation.
A simple example:
And so, you need from such data:
var data = { title: 'C pocket reference', type: 'PDF Document', tag: 'programming', // In order not to complicate, let the tag be one created_at: '5.31.2010' }
get this html:
C pocket reference PDF Document programming 5/1/2010
Proceed:
var html = '' + data.title + '' + data.type + ' ' + data.tag + ' ' + data.created_at + ''
Somehow scary. Options ??
Add the supplant method from Douglas Crockford to the String prototype:
String.prototype.supplant = function (o) { return this.replace (/ {([^ {}] *)} / g, function (a, b) { var r = o [b]; return typeof r === 'string' || typeof r === 'number'? r: a; } ); };
The essence of the method is to go over the properties of the object received in the parameters, which were in the line and were enclosed in curly braces and replace the property names with their values. All this is similar to the Ruby # #} construct, which allows variable values to be inserted into a string without concatenation.
We try:
var html = '{title} {type} {tag} {created_at}'. supplant (data)
Pros:
- no need to concatenate strings
- before each property you do not need to write the name of the object