2010-12-07 7 views
3
<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['$1']); 

</script> 

답변

4

를 사용하여 교체하는 기능 :

<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> 
+0

나는 이것을 몰랐다! 매일 학교 생활 .. .. 고마워! – Connell

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

사용에 대한 당신은 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] || ""; 
}); 

또는 :

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); 
관련 문제