📜 ⬆️ ⬇️

Some templating

Not so long ago, from a lecture by Douglas Crockford, I learned about a very interesting technique of “templating” in JavaScript. The main purpose of the technique is that we receive from the server JSON and then somehow form of this HTML. In many situations, this process leaves much to be desired because HTML is generated either by concatenating strings or creatingElement, appendChild, etc. operations. Perhaps many already know about this decision, but for those who did not know, I hope it will be useful.

A simple example:

And so, it is necessary from such data:
 var data = {
   title: 'C pocket reference',
   type: 'PDF Document',
   tag: 'programming', // So as not to complicate, let the tag be one
   created_at: 'May 5, 2010'
 }

get this html:

  <tr>
   <td> C pocket reference </ td>
   <td> PDF Document </ td>
   <td> <a href="tags/programming"> programming </a> </ td>
   <td> 05.31.2010 </ td>
 </ tr> 

Let's start:

 var html = '<tr> <td>' + data.title + '</ td> <td>' + data.type + '</ td> <td> <a href = "tags /' + data.tag + '" > '+ data.tag +' </a> </ td> <td> '+ data.created_at +' </ td> </ tr> ' 

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 run through the properties of the object obtained in the parameters that were in the string and were enclosed in braces and replace the names of the properties with their values. All this is similar to Ruby's # {} construct, which allows you to insert variable values ​​into a string without concatenation.

We try:

 var html = '<tr> <td> {title} </ td> <td> {type} </ td> <td> <a href="tags/{tag}"> {tag} </a> < /td><td>{created_at}<</td></tr>'.supplant(data)

Pros:
Highlight such designs in the editor and it will be wonderful.

Source: https://habr.com/ru/post/96588/


All Articles