Rather than
<input type="submit" />
I want to output
<button>
using the button_to method (开发者_JAVA技巧rails 3.0.0)
Is this possible?
As of the latest version of Rails (4.0.2, not sure about previous versions) passing a block to button_to invokes branch logic in the helper that creates a button element instead of an input.
For example, if you wanted to make a 'delete' button element in haml, bootstrap & fontawesome (my use case):
= button_to(foo_path(@foo),
class: 'btn btn-sm', method: :delete, remote: true) do
<i class="fa fa-times"></i>
If you want them to just always be button elements no matter what, you could always have your button content inside a block instead of the first argument. Not sure what the trade-off is there.
You could override the button_to
helper in ApplicationHelper
to render a button
tag instead. Look at the code that button_to
already has and modify it to suit your purposes.
I just found that changing button_to to using a block generates button tag instead of input:
so:
<%= button_to account_path(@account), data: {confirm: 'Are you sure?'}, method: :delete, class: 'btn btn-default btn-danger' do %>
Inactivate
<% end %>
Generates:
<form method="post" class="button_to" action="/accounts/30">
<div>
<input type="hidden" value="delete" name="_method">
<button type="submit" data-confirm="Are you sure?" class="btn btn-default btn-danger">
Inactivate
</button>
<input type="hidden" value="" name="authenticity_token">
</div>
</form>
from what i can see Rails already has a helper to output tags; it's called button_tag
(instead of button_to
).
so, you could just use the following in your views, i see no need to override button_to:
<%= button_tag "Button Text", :class => "btn", :type => "submit" %>
no need to override. also, it's recommended to always supply the :type parameter since is rendered different in different browsers.
I generally just stick this in my application_helper.rb file:
def button_tag(text, options={})
content_tag(:button, {:type => "submit"}.merge(options)) { text }
end
You can then call it from a view like so:
button_tag "Save", :class => 'accept'
In Rails 7, the button_to
view helper will render a <button>
element, regardless of whether or not the content is passed as the first argument or as a block.
精彩评论