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)

标签: none

添加新评论