Skip to content

Instantly share code, notes, and snippets.

@L422Y
Created February 25, 2013 20:58
Show Gist options
  • Save L422Y/5033233 to your computer and use it in GitHub Desktop.
Save L422Y/5033233 to your computer and use it in GitHub Desktop.
A CodePen by Larry Williamson. Template fill w/ split() - Uses String.split() to break up a template using a RegEx wrap match. Then iterates odd items, replacing the template variable name with the value if there is a matching definition
<div>This {!template!} has {!variables!} in it.</div>
<button id='fill'>Fill Template</button>
var $tpl = {
wrap: /\{!|!\}/,
fillElement: function(selector,fill_data){
var template_body = $(selector).html();
$(selector).html($tpl.fill(template_body,fill_data));
},
fill: function(template_body,fill_data){
var tpl_split = template_body.split($tpl.wrap);
var tpl_split_count = tpl_split.length;
for(var idx=1;idx<tpl_split_count;idx+=2){
if(fill_data.hasOwnProperty(tpl_split[idx])) {
tpl_split[idx] = fill_data[tpl_split[idx]];
}
}
return tpl_split.join('');
}
};
$('#fill').click(function(){
$tpl.fillElement(
'div',
{
"template": "page",
"variables": "content"
}
);
});
@import "compass";
body {
background:#222222;
color:#999;
text-align:center;
div {
font-size:20px;
text-align:center;
margin:0 auto;
width:auto;
padding:100px 0 50px;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment