Skip to content

Instantly share code, notes, and snippets.

@edds
Last active August 29, 2015 14:11
Show Gist options
  • Save edds/65d931d14d56f8ab1eca to your computer and use it in GitHub Desktop.
Save edds/65d931d14d56f8ab1eca to your computer and use it in GitHub Desktop.
Render mustache templates natively in Rails using a template handler
# ./config/initializers/mustache_template.rb
class MustacheTemplate
# `call` returns a string which is evaled in the context of the action view
# This follows the same pattern as other handlers:
# https://github.com/rails/rails/tree/4-2-stable/actionview/lib/action_view/template/handlers
def call(template)
partial_prefix = File.basename(File.dirname(template.identifier))
<<-cmd
mustache_template = Mustache.new
mustache_template.instance_variable_set("@view_paths", view_paths)
def mustache_template.partial(name)
partial = @view_paths.find(name, '#{partial_prefix}', true, { formats: [:html], locale: [], handlers: [:mustache] })
partial.source
end
mustache_template.template = '#{template.source.gsub(/'/, "\\\\'")}'
mustache_template.render(local_assigns).html_safe
cmd
end
end
ActionView::Template.register_template_handler(:mustache, MustacheTemplate.new)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment