Nodejs String Template template(fn, object)

Here you can find the source of template(fn, object)

Method Source Code

// accepts optional transformer
// now transformers are compatible with ES6
String.prototype.template = function (fn, object) {'use strict';
  // Andrea Giammarchi - WTFPL License
  var/*  w w  w.j  a va 2 s . c  o  m*/
    hasTransformer = typeof fn === 'function',
    stringify = JSON.stringify,
    re = /\$\{([\S\s]*?)\}/g,
    strings = [],
    values = hasTransformer ? [] : strings,
    i = 0,
    str,
    m
  ;
  while ((m = re.exec(this))) {
    str = this.slice(i, m.index);
    if (hasTransformer) {
      strings.push(str);
      values.push('(' + m[1] + ')');
    } else {
      strings.push(stringify(str), '(' + m[1] + ')');
    }
    i = re.lastIndex;
  }
  str = this.slice(i);
  strings.push(hasTransformer ? str : stringify(str));
  if (hasTransformer) {
    str = 'function' + (Math.random() * 1e5 | 0);
    strings = [
      str,
      'with(this)return ' + str + '(' + stringify(strings) + (
        values.length ? (',' + values.join(',')) : ''
      ) + ')'
    ];
  } else {
    strings = ['with(this)return ' + strings.join('+')];
  }
  return Function.apply(null, strings).call(
    hasTransformer ? object : fn,
    hasTransformer && fn
  );
};

Related

  1. template()
    String.prototype.template = function () {
      var current = this;
      function safeRegexEscape(str) {
        return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
      for (var i = 0; i < arguments.length; i++) {
        var arg = arguments[i];
        current = current.replace(new RegExp(safeRegexEscape("%%")), arg);
      return current;
    };
    
  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;
      });
    };