Created
September 22, 2011 23:03
-
-
Save exogen/1236283 to your computer and use it in GitHub Desktop.
Milk (Mustache) template engine for Knockout
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
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