new.html.erb
<%= form_for @star do |f|%>
<%= star_radio(f, true)%>
<% end %>
stars_helper.rb
module StarHelper
def star_radio(form, status)
form.label "star_#{status}", class: 'radio-inline' do
form.radio_button(:star, status) + i18n_star(status)
end
end
def i18n_star (status)
I18n.t("activerecord.attributes.star.is_sun.#{status}")
end
end
我看到了上面的一段代码
我不熟悉自定义表单助手
你能告诉我为什么我们可以在一个区块内使用form.radio_button(:star, status) + i18n_star(status)
以及为什么我们可以使用&#39; +&#39;在单选按钮上添加文本
如果你能告诉我在哪里可以学到这一点,我将不胜感激。
答案 0 :(得分:1)
form.radio_button
helper返回一个字符串,I18n.t
也返回一个字符串。所以,你可以连接它们。
详细说明如何生成表单标记
这是radio_button
的代码:
https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/form_helper.rb
def radio_button(object_name, method, tag_value, options = {})
Tags::RadioButton.new(object_name, method, self, tag_value, options).render
end
查看render方法的实现
def render
options = @options.stringify_keys
options["type"] = "radio"
options["value"] = @tag_value
options["checked"] = "checked" if input_checked?(object, options)
add_default_name_and_id_for_value(@tag_value, options)
tag("input", options)
end
标记助手生成html标记并将其作为html安全字符串返回:
https://github.com/casunlight/rails/blob/master/actionview/lib/action_view/helpers/tag_helper.rb#L67
def tag(name, options = nil, open = false, escape = true)
"<#{name}#{tag_options(options, escape) if options}#{open ? ">" : " />"}".html_safe
end