Skip to content

Instantly share code, notes, and snippets.

@unders
Forked from dbi/edit.html.mustache
Created July 6, 2012 08:50
Show Gist options
  • Save unders/3059027 to your computer and use it in GitHub Desktop.
Save unders/3059027 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment