Skip to content

Instantly share code, notes, and snippets.

@nickjacob
Last active December 14, 2015 06:39
Show Gist options
  • Save nickjacob/5044484 to your computer and use it in GitHub Desktop.
Save nickjacob/5044484 to your computer and use it in GitHub Desktop.
impl of my picotemplate in coffeescript to see what it'd be like
__deep = (obj, prop) ->
for p in prop.split '.'
if not (p in obj and obj = obj[p])
return undefined
obj() if typeof obj is 'function' else obj
getEscape = (tpl) ->
qq = "\'" if '"' in tpl else "\""
(str) -> qq + str + qq
_tplRegexp = /{{\s*([\w\.]+)\s*}}/ig
tplReplace = (str, m) ->
__qq("__deep(obj, #{ __qq(m) })") if /\./g.test(m) else __qq("((typeof(#{ m }) !== #{ __qq('function') }) ? #{ m } : #{ m }())")
compile = (tpl) ->
__qq = getEscape tpl
Function ['obj'], "var __qq = #{ __qq.toString() }; with (obj) return #{ __qq(tpl.replace(/['"]/g, "\$&").replace(_tplRegexp, tplReplace) }; }"
window.µ = compile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment