Skip to content

Instantly share code, notes, and snippets.

@kevburnsjr
Created January 24, 2016 15:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevburnsjr/8a77a02b219a615ff530 to your computer and use it in GitHub Desktop.
Save kevburnsjr/8a77a02b219a615ff530 to your computer and use it in GitHub Desktop.
Microtemplating example
<!--
This is snippet is free to use without attribution, published under wtfpl-2.0
https://tldrlegal.com/license/do-wtf-you-want-to-public-license-v2-(wtfpl-2.0)
-->
<html>
<head>
<title>Microtemplate example</title>
</head>
<body>
<div id="target"></div>
<script type="text/template" id="tpl-option">
<option value="{{value}}" {{{selected}}}>{{label}}</option>
</script>
<script>
(function(){
"use strict";
var Template = function(src) {
var fields_literal = [],
fields_escaped = [];
(src.match(/\{\{\{([a-z]+)\}\}\}/g) || []).forEach(function(v){
fields_literal.push(v.substr(3,v.length-6));
});
(src.match(/\{\{([a-z]+)\}\}/g) || []).forEach(function(v){
fields_escaped.push(v.substr(2,v.length-4));
});
var escape = function(input) {
return input.replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/"/g, '&quot;')
.replace(/</g, '&lt;').replace(/>/g, '&gt;');
};
return {
render : function(data){
var out = src;
fields_literal.forEach(function(f){
out = out.replace('{{{'+f+'}}}', f in data ? data[f] : "");
});
fields_escaped.forEach(function(f){
out = out.replace('{{'+f+'}}', f in data ? escape(data[f]) : "");
});
return out;
}
};
};
var t = new Template(document.getElementById('tpl-option').innerHTML);
document.getElementById('target').innerHTML = t.render({
value: "hello",
selected: "selected='selected'",
label: "Hello, world"
});
})();
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment