Skip to content

Instantly share code, notes, and snippets.

@hijonathan
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save hijonathan/60fd87cf54b9bb54e9e0 to your computer and use it in GitHub Desktop.

Select an option

Save hijonathan/60fd87cf54b9bb54e9e0 to your computer and use it in GitHub Desktop.
Super simple js templating
# Regex for ONE optional whitespace.
# NOTE: Replace `?` with `*` to make it more lenient.
nbsp = '[\\s\\xA0]\?'
templatize = (str, context) ->
# If no object just return string.
if not context or typeof context isnt 'object'
return str
# Loop through keys and replace placeholders.
for key of context
# Max ONE whitespace on either end.
# E.g. matches {{foo}}, {{ foo}} and {{ foo }}, but
# not {{ foo }} or {{ foo}}.
re = new RegExp("{{#{nbsp}#{key}#{nbsp}}}", 'g')
str = str.replace re, context[key]
return
return str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment