Skip to content

Instantly share code, notes, and snippets.

@chunpu
Last active August 29, 2015 13:56
Show Gist options
  • Save chunpu/9320339 to your computer and use it in GitHub Desktop.
Save chunpu/9320339 to your computer and use it in GitHub Desktop.
a simple and stupid html template
<script src='./template.js'></script>
<script id='tmpl' type='x'>
<p>Hi {{=name}}</p>
<ul>
{{for (var i = -1; i++ != arr.length - 1;) { }}
<li>{{=arr[i]}}</li>
{{ } }}
</ul>
</script>
<div>
</div>
<script>
function $(sel) {
return document.querySelector(sel)
}
$('div').innerHTML = tmpl($('#tmpl'), {name: 'monkey', arr: [1, 2, 3, 4]})
</script>
function tmpl(el, opt) {
var src = el.innerHTML
var arr = ['with(opt) {var ret = ""']
src.split('{{').forEach(function(x, i) {
var two = x.split('}}')
if (two[1]) {
genJS(two[0].trim())
return filter(two[1])
}
filter(two[0])
})
function genJS(jsstr) {
if (jsstr[0] === '=') arr.push('ret += ' + jsstr.substr(1))
else arr.push(jsstr)
}
function filter(html) {
arr.push('ret += "' + html.replace(/('|"|\\)/g, '\\$1').replace(/\r/g, '\\r').replace(/\n/g, '\\n') + '"')
}
arr.push('return ret}')
return new Function('opt', arr.join('\n'))(opt)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment