2010-10-26 61 views
0

我有这行:如何使button_to的html输出具有单引号而不是双引号?

<%= button_to 'Post', newpost_path(:type => 'short_note') %> 

它输出这样的:

<form method="post" action="/posts/newpost?type=short_note" class="button-to"><div><input type="submit" value="Add" /></div></form>; 

但我需要的输出有单引号,不是一倍。我怎样才能做到这一点?

<form method='post' action='/posts/newpost?type=short_note' class='button-to'><div><input type='submit' value='Add' /></div></form>; 

回答

1

试试这个:

<%= (button_to 'Post', newpost_path(:type => 'short_note')).gsub('"', '\'') %> 
0

我认为,唯一的办法就是gsub(/"/, "'"),但这实在是太丑了

1

创建RAILS_ROOT文件/ lib目录称为url_helper_overrides.rb那只是将按钮重写为方法。或者你可以将下面的button_to方法添加到你的application_helper。这种方法直接从UrlHelper source in Rails (Github Link)中取出,我简单地用双引号替换了双引号。

module ActionView 
    module Helpers 
    module UrlHelper 

     def button_to(name, options = {}, html_options = {}) 
     html_options = html_options.stringify_keys 
     convert_boolean_attributes!(html_options, %w(disabled)) 

     method_tag = '' 
     if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s) 
      method_tag = tag('input', :type => 'hidden', :name => '_method', :value => method.to_s) 
     end 

     form_method = method.to_s == 'get' ? 'get' : 'post' 

     remote = html_options.delete('remote') 

     request_token_tag = '' 
     if form_method == 'post' && protect_against_forgery? 
      request_token_tag = tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) 
     end 

     url = options.is_a?(String) ? options : self.url_for(options) 
     name ||= url 

     html_options = convert_options_to_data_attributes(options, html_options) 

     html_options.merge!("type" => "submit", "value" => name) 

     ("<form method='#{form_method}' action='#{html_escape(url)}' #{"data-remote='true'" if remote} class='button_to'><div>" + 
      method_tag + tag("input", html_options) + request_token_tag + "</div></form>").html_safe 
     end 
    end 
    end 
end