Created
December 3, 2012 22:33
-
-
Save stevenschobert/4198756 to your computer and use it in GitHub Desktop.
Quick 'n Easy template parser in CoffeeScript
This file contains 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
# ------------------------------------------------------ | |
# Really simple template parser in CoffeeScript. | |
# Matches {{keyword}} syntax. | |
# Input: string, object | |
# Output: string | |
# | |
# Ex: templar("Hello {{planet}}!", {planet: "World"}); | |
# -> outputs "Hello World!" | |
# ------------------------------------------------------ | |
templar = (input, data) -> | |
pattern = /// | |
(?:\{{2}) # opening braces | |
(\w+) # variable name | |
(?:\}{2}) # closing braces | |
/// | |
output = input | |
while (pattern.test(output)) | |
varName = output.match(pattern)[1] | |
output = output.replace(pattern, "#{data[varName]}") | |
return output |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I wrote this really bare-bones template parser for a recent project. Comes in super handy if you need to quickly add some on-the-fly templating to your project, or don't want to weigh it down with a full-fledged library like Mustache! :)