返回列表

两种不同思路的字符串模板替换

默认分类 2017/07/03 21:21

方式一

function template1(source, opts) {
  source = String(source);
  var data = Array.prototype.slice.call(arguments, 1);
  if (data.length) {
    data = (data.length === 1 ? (opts !== null && (/\[object (Array|Object)\]/.test(Object.prototype.toString.call(opts))) ? opts : data) : data);
    return source.replace(/#\{(.+?)\}/g, function(match, key) {
      var part, parts = key.split('.'),
        cur = data,
        part = parts.shift()
      while (cur && part) {
        cur = cur[part] !== undefined ? cur[part] : undefined
        part = parts.shift()
      }
      return (undefined === cur ? '' : cur)
    })
  }
}

方式二

function template2(tpl, data) {
  var tmp = tpl;
  tmp = tmp.replace(/(^|\r|

)\t* | *\t(\r| |$)/g, ''); tmp = tmp.replace(/\$\{([\s\S]+?)\}/g, function(m, code) { code = unescape(code); var list = code.split('|'); var s1 = list.shift(); return '\';out+=(' + s1 + ');out+=\''; }); var str = ('with(it){ var out=\'' + tmp + '\'; return out;}'); str = str.replace(/(\s|;|\}|^|\{)out\+='';/g, '$1').replace(/\+''/g, ''); try { var fn = new Function('it', str); } catch (e) { if (typeof console !== 'undefined') console.log('Create template function error: ' + str); throw e; } return data === undefined ? fn : fn(data) }