Skip to content

Instantly share code, notes, and snippets.

@exogen
Created September 22, 2011 23:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exogen/1236283 to your computer and use it in GitHub Desktop.
Save exogen/1236283 to your computer and use it in GitHub Desktop.
Milk (Mustache) template engine for Knockout
ko = require 'knockout'
Milk = require 'milk'
class Template
constructor: (@string) ->
render: (data, options) =>
# Knockout expects an Array-like object of Nodes.
# We could just use createElement and set innerHTML,
# but apparently jQuery's append does some kind of cleanup.
# So, let's assume jQuery solves some kind of problem for us.
parent = $(options.parent ? '<div/>')
markup = Milk.render @string, data
parent.append markup
# Be cautious; don't apply bindings to the node itself, just what
# was in the template (its children).
for child in parent.children()
ko.applyBindings data, child
parent.contents() # Includes text and comment nodes.
class TemplateEngine extends ko.templateEngine
constructor: (@templates) ->
getTemplate: (name) =>
string = @templates[name]
if string?
new Template string
else
throw new TemplateNotFound "'#{name}'"
renderTemplate: (name, data, options) =>
template = @getTemplate name
template.render data, options
isTemplateRewritten: =>
rewriteTemplate: =>
createJavaScriptEvaluatorBlock: =>
class TemplateNotFound
module.exports = {Template, TemplateEngine, TemplateNotFound}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment