开发者

How to pass Javascript back reference to key or function?

<script type='text/javascript'>

 // I have template and info
 var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
 var img_info = {
  src : 'http://myimage.com/img.jpg',
  width: '100px',
  height: '100px',
  title: 'My Image'
 }

 // I want to put info to template but It's not work.
 // How should I do ?
 var my_image = img_template.replace(/{(.+?)}/g, img_info[开发者_StackOverflow社区'$1']);

</script>


Use a function for the replacement:

<script type='text/javascript'>
 var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
 var img_info = {
  src : 'http://myimage.com/img.jpg',
  width: '100px',
  height: '100px',
  title: 'My Image'
 }

 var my_image = img_template.replace(/{(.+?)}/g, function(a,b){
      return img_info[b];
 });
</script>


var my_image = img_template.replace(/{(.+?)}/g, function(m,v){return img_info[v];});

example at http://www.jsfiddle.net/gaby/3Lu4h/

more about using a function as a parameter to the replace method


var my_image = img_template.replace(/{(.+?)}/g, function(match, group1){
  return img_info[group1];
});


You need a callback function for the replace().

var img_template = "<img src='{src}' width='{width}' height='{height}' title='{title}' />";
var img_info = {
  src : 'http://myimage.com/img.jpg',
  width: '100px',
  height: '100px',
  title: 'My Image'
};

// callback function will be executed for each match
var my_image = img_template.replace(/{([^}]+)}/g, function(match, group1) {
  // return lookup value or the empty string
  return img_info[group1] || "";
});

Or, in re-usable form:

function HtmlTemplate(html) {
  this.template = html;
  this.render   = function(info) {
    return this.template.replace(/{([^}]+)}/g, function(match, group1) {
      return info[group1] || "";
    });
  };
}

var imgTemplate = new HtmlTemplate("<img src='{src}' width='{width}' height='{height}' title='{title}' />");

// later

var img = imgTemplate.render(img_info);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜