Skip to content

Instantly share code, notes, and snippets.

@dbi
Created May 4, 2011 09:31
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save dbi/954994 to your computer and use it in GitHub Desktop.
Save dbi/954994 to your computer and use it in GitHub Desktop.
Rails form helper for mustache spike/proof of concept
<!-- A scaffolded edit view converted to mustache -->
<h1>Editing post</h1>
{{#form}}
{{#errors?}}
<div id="error_explanation">
<h2>{{error_header}}</h2>
</div>
<ul>
{{#errors}}
<li>{{.}}</li>
{{/errors}}
</ul>
{{/errors?}}
<div class="field">
{{title_label}}<br />
{{title_input}}
</div>
<div class="field">
{{body_label}}<br />
{{body_input}}
</div>
<div class="field">
{{author_label}}<br />
{{author_input}}
</div>
<div class="actions">
{{submit}}
</div>
{{/form}}
{{{show_link}}}
{{{back_link}}}
require "mustache_extras"
class Posts::Edit < Mustache::Rails
include Mustache::FormBuilder
def form
formable(@post) do |f|
{
:title_label => f.label(:title),
:title_input => f.text_field(:title),
:body_label => f.label(:body),
:body_input => f.text_area(:body),
:author_label => f.label(:author),
:author_input => f.text_field(:author),
:submit => f.submit
}
end
end
def errors?
@post.errors.any?
end
def error_header
"#{pluralize(@post.errors.count, "error")} prohibited this post from being saved:"
end
def errors
@post.errors.full_messages
end
def show_link
link_to 'Show', @post
end
def back_link
link_to 'Back', posts_path
end
end
module Mustache::FormBuilder
def formable(object)
lambda do |text|
form_for(object) do |f|
obj = FormableMustache.new(yield(f))
Mustache.render(text, obj).html_safe
end
end
end
end
class FormableMustache < Mustache
def initialize(data)
data.each_pair do |key, value|
FormableMustache.send(:define_method, key, proc{value})
end
end
def escapeHTML(str)
str
end
end
@marnen
Copy link

marnen commented Sep 2, 2011

Oh, this looks great. FormBuilders are what's been keeping me from trying Mustache with Rails. I'll have to play with this now.

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