Skip to content

Instantly share code, notes, and snippets.

@hopsoft
Created January 10, 2012 16:45
Show Gist options
  • Save hopsoft/1589957 to your computer and use it in GitHub Desktop.
Save hopsoft/1589957 to your computer and use it in GitHub Desktop.
Rails + Backbone + Underscore templates
# sprockets.rb
# monkey patch to sprockets for evaluate_template
module Blisten
module Sprockets
module Context
# Evaluates a Backbone style HTML template.
# This is basically Sprockets::Context#evaluate
# with some special rules applied.
def evaluate_template(path)
evaluate(path).escape("'", '"').gsub(/\n|\t/, "")
end
end
end
end
::Sprockets::Context.send(:include, Blisten::Sprockets::Context)
module Blisten
module String
# Escapes a series of chars in the current string.
# Note that a new string is returned.
def escape(*chars)
gsub(/(?<!\\)(#{chars.join("|")})/) do |char|
"\\" + char
end
end
end
end
::String.send(:include, Blisten::String)
// view.js.erb
// render method in the backbone view
render: function() {
if (!this.template) {
this.template = _.template("<%= evaluate_template("./discover.html") %>");
}
this.$el.html(this.template(this.model.attributes));
return this;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment