Created
February 25, 2013 20:58
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div>This {!template!} has {!variables!} in it.</div> | |
<button id='fill'>Fill Template</button> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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