Created
January 24, 2016 15:12
-
-
Save kevburnsjr/8a77a02b219a615ff530 to your computer and use it in GitHub Desktop.
Microtemplating example
This file contains hidden or 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
<!-- | |
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, '&').replace(/'/g, ''').replace(/"/g, '"') | |
.replace(/</g, '<').replace(/>/g, '>'); | |
}; | |
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