Last active
August 29, 2015 14:06
-
-
Save hijonathan/60fd87cf54b9bb54e9e0 to your computer and use it in GitHub Desktop.
Super simple js templating
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
| # 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