Nodejs String Template tmpl(obj)

Here you can find the source of tmpl(obj)

Method Source Code

String.prototype.tmpl = function(obj){
    var str, keys, _do;

    //store string
    str = this.toString();/*from w w  w .j  a  v a  2 s .co  m*/

    //if no object just return string
    if(!obj || typeof obj !== "object"){
        return str;
    }

    //get keys in object
    keys = Object.keys(obj);

    //loop through keys and replace place holders
    _do = function(key){
        var rgx = new RegExp("#{"+key+"}", "g");
        str = str.replace(rgx, obj[key]);
    };

    keys.forEach(_do);

    return str;
}

Related

  1. template(fn, object)
    String.prototype.template = function (fn, object) {'use strict';
      var
        hasTransformer = typeof fn === 'function',
        stringify = JSON.stringify,
        re = /\$\{([\S\s]*?)\}/g,
        strings = [],
        values = hasTransformer ? [] : strings,
        i = 0,
        str,
    ...
    
  2. template(map)
    String.prototype.template=function(map){
        return $(this.replace(/{([^}]+)}/g, function(m,g) {
            console.log(map, m,g)
            var segments = g.split('.');
            var val = map;
            for(var i in segments) {
                val=val[segments[i]];
            return val;
    ...
    
  3. template(objVar)
    String.prototype.template = function (objVar)
      var strVar = this;
      if(typeof objVar === "object")
        var length = strVar.length;
        var start = -1;
        var key = "";
        for(var index = 0; index < length; index++)
    ...
    
  4. tmpl(d)
    String.prototype.tmpl = function(d) {
      return this.replace(/\$\$([^$]+)\$\$/g,
        Function('d', 'return function(_,s){with(d) return eval(s)}')(d||{}))
    };
    
  5. tmpl(o)
    String.prototype.tmpl = function(o) {
      return this.replace(/\{([^{}]*)\}/g, function(a, b) {
        var r = o[b];
        return typeof r === 'string' || typeof r === 'number' ? r : a;
      });
    };