提问人:Santiago Ospina Idrobo 提问时间:3/14/2023 最后编辑:Santiago Ospina Idrobo 更新时间:3/15/2023 访问量:96
如何在simple_form_for中为输入添加背景图像 - Rails
How can I add a background image to an input in a simple_form_for - Rails
问:
我正在 rails 中创建一个简单的表单来创建一个新帐户,每个帐户都必须有自己的图标。但我不知道如何使用图标关联将input_html添加到各自的图标图像中。
我正在尝试显示图标列表,图标有一个 url,它们的帐户中有一个外键,所以我正在使用它:
<%= simple_form_for [@account], data: { account_card_target: "form" } do |f| %>
<div class="form-inputs">
<%= f.input :account_name %>
<%= f.input :account_type,
collection: ['***', '***', '***', '***'],
prompt: "Select a type" %>
<%= f.input :balance %>
<%= f.input :account_number %>
<%= f.association :icon,
as: :radio_buttons,
label_method: ->(icon) { "<label class='icon-radio-label' for='my-input' style='background-image: url(#{cl_image_path(icon.url)})'></label>".html_safe },
value_method: :id,
input_html: { class: 'my-input', id: 'my-input' }
%>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
但是在此代码中,我将背景添加到标签中,并且我希望将标签设置为空并在输入中使用背景图像。
如果我使用它,我可以将 bg 图像添加到输入中,但我不知道如何替换 icon.url 的“saving_icon”,因为我尝试使用 lambda 但仍然不起作用
<%= f.association :icon,
as: :radio_buttons,
label_method: ->(icon) { " " },
value_method: :id,
input_html: {
class: "icon-radio",
style: "background-image: url(#{cl_image_path('saving_icon')});"
}
%>
任何关于实现这一点的提示都会受到好评,谢谢!
答:
我不是很精通simple_form,但我可以给出一些建议。
不幸的是,我看不到任何地方说参数(或类似参数)可以以与 或 相同的方式获取 lambda。input_html
label_method
value_method
但是,我能够找到与此相关的 GitHub 问题simple_form - 请特别查看此评论。看起来 HTML 属性可以作为参数中的第三个数组元素包含在内。因此,您也许可以使用这样的东西(非常未经测试):collection
f.association :icon,
# ...
collection: Icon.all.map do |icon|
[
icon.name,
icon.id,
{ style: "background-image: url(#{cl_image_path(icon.url)})" },
]
end
或者,定义自定义输入看起来可以为您提供所需的所有灵活性。
或者,通过对要生成的 HTML 进行这种自定义,自己生成所需的 HTML 可能更简单,跳过对这组单选按钮使用 simple_form。
我看到你已经添加了标签。Rails 3 已停产
几年前,因此没有收到安全更新。如果你还在运行 Rails 3,我强烈建议你升级。ruby-on-rails-3
评论
多亏了ZimbiX的帮助,我才能解决这个问题,所以:
<%= f.association :icon,
as: :radio_buttons,
collection: Icon.all.map { |icon| [icon.url, icon.id, style: "background-image: url(#{cl_image_path(icon.url)});"] }
%>
所以在集合中,第三个参数是input_html的 HTML,这对我来说太好了。
评论