Skip to content

Instantly share code, notes, and snippets.

@stevenschobert
Created December 3, 2012 22:33
Show Gist options
  • Save stevenschobert/4198756 to your computer and use it in GitHub Desktop.
Save stevenschobert/4198756 to your computer and use it in GitHub Desktop.
Quick 'n Easy template parser in CoffeeScript
# ------------------------------------------------------
# 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
@stevenschobert
Copy link
Author

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! :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment