Skip to content

Instantly share code, notes, and snippets.

@foca
Created October 5, 2009 16:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save foca/202208 to your computer and use it in GitHub Desktop.
Save foca/202208 to your computer and use it in GitHub Desktop.
require "mustache"
ActiveSupport::Dependencies.load_paths << Rails.root.join("app", "views")
class Mustache::Rails < Mustache
include ActionController::UrlWriter
include ActionView::Helpers
attr_accessor :request, :response, :params, :controller
# ActionView::Helpers overrides the +render+ method, so we need to copy it
# back from Mustache. Ugly, I know :(
def render(html, context = {})
@context = context = (@context || {}).merge(context)
html = render_sections(html)
@context = context
render_tags(html)
end
# Use rails' html_escape ("h") for escaping.
alias_method :escape, :html_escape
end
class Mustache::Rails::TemplateHandler < ActionView::TemplateHandler
def render(template, local_assigns)
mustache_class_name = template.path.gsub(".html.mustache", "").classify
mustache_class = mustache_class_name.constantize
result = mustache_class.new
copy_instance_variables_to(result)
result.template_file = Rails.root.join("app", "views", template.path)
result.controller = @view.controller
result.request = result.controller.request
result.response = result.controller.response
result.params = result.controller.params
result.to_html
end
def copy_instance_variables_to(mustache)
variables = @view.controller.instance_variable_names
variables -= %w(@template)
variables -= @view.controller.protected_instance_variables if @view.controller.respond_to?(:protected_instance_variables)
variables.each {|name| mustache.instance_variable_set(name, @view.controller.instance_variable_get(name)) }
end
end
ActionView::Template.register_template_handler(:mustache, Mustache::Rails::TemplateHandler)
@agibralter
Copy link

What do you think about having render take a view (the .rb file) instead of the mustache template? I kind of want to put my mustache templates in app/mustache_templates/... (so I can share them easily with client-side JS) and my mustache views in app/views/... (e.g. app/views/posts/show.rb app/mustache_templates/posts/show.html.mustache)

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