js微型模板系统


var Template = function(template, pattern){
  this.template = String(template);
  this.pattern = pattern || Template.Pattern;
}
Template.Pattern = /#\{([^}]*)\}/mg;
Template.trim = String.trim || function(str){
  return str.replace(/^\s+|\s+$/g, '')
}
Template.prototype ={
  constructor:Template,
  compile: function(object) {
    return this.template.replace(this.pattern, function(displace,variable){
      variable = Template.trim(variable)
      return displace = object[variable]
    });
  }
}
var data = "<div>Name: <b>#{name}</b>  Blog: <a href='#{href}'>#{blog }</a></div>";
var t = new Template(data);
var objs = {name:"mark",
   blog:"RubyLouvre",
   href:"http://www.cnblogs.com/rubylouvre/"}
var result = t.compile(objs);
alert(result)

声明:Mr.xu|版权所有,违者必究|如未注明,均为原创|本网站采用BY-NC-SA协议进行授权

转载:转载请注明原文链接 - js微型模板系统


Carpe Diem and Do what I like