JavaScript templates

    sometimes when using ajax it is necessary to replace large html blocks, it is not always convenient to create a bunch of DOM elements so that the formatting remains the same as it was. Some of them pass the html code directly to the ajax and paste it into the right place, but the prototype developers made a more successful implementation, when it is possible to transfer only data in the form of JSON from the server, and then paste them into a separate template using JavaScript ... it’s exactly with them that I I borrowed the idea, having simplified it

    a little, such a small classic implements the functions of a template engine in JavaScript, it’s quite simple to use it:

    1 - we connect the class
    1. function Template( template )
    2. {
    3.   var _template = template.toString();
    4.   var _pattern = /(#\{.*?\})/g;
    5.   this.evaluate = function(object)
    6.   {
    7.     if( !( object instanceof Array ) )
    8.     {
    9.       object = new Array( object );
    10.     }
    12.     var result = '';
    13.     for( var q = 0; q < object.length; q++ )
    14.     {
    15.       var tmpTemplate = _template;
    16.       result += tmpTemplate.replace(_pattern, function(match)
    17.       {
    19.         var key = match.substring(2, match.length-1);
    20.         if( undefined !== object[q][key] )
    21.         {
    22.           return object[q][key];
    23.         }
    24.         return '';
    25.       });
    26.     }
    27.     return result;
    28.   }
    29. };
    * This source code was highlighted with Source Code Highlighter.

    2 - create a template that we will need (each variable is separated # {- in front and} - in the back):
    var template = '
    # {someText} # {otherText}

    3 - create an object to work with the template
    var templateParser = new Template (template);

    well, actually we get ready html code that can be inserted anywhere based on your data, the
    object keys must match the variables in the template, if the key is not in the template it is ignored
    and if extra variables remain in the template then they are deleted
    var htmlData = templateParser.evaluate ( {someText: 'to view comments', href: '/ comments', otherText: 'click here'});

    in the end there will be such a line:
    to view comments click here

    upd: yes! this method works slower than adding via the DOM, but it saves the code with larger attachments of elements per person

    upd2: I changed the code, tested it on firefox, it works 2 times faster than through the DOM, the example is weak:


        Элемент0 нажми для перехода


    * This source code was highlighted with Source Code Highlighter.

    Also popular now: