Rails 7.1中如何将视图代码转为Helper方法?span未渲染问题求解
Rails 7.1视图代码迁移至Helper方法的修正方案
问题根源
Ruby块中默认仅返回最后一个表达式的执行结果,你编写的primary_button方法里,content_tag("span", text, class: "b")的输出被直接丢弃,最终只返回了svg(icon)的内容,导致span标签未渲染。另外还存在参数错误:原视图中button_tag的type为"submit"、class为"a",你在helper里误将type设为"a",需要同步修正。
修正后的Helper方法
module ApplicationHelper def svg(name) file = Rails.root.join("app", "assets", "images", "#{name}.svg") File.read(file).html_safe end def primary_button(text:, icon:) button_tag type: "submit", class: "a" do # 拼接两个HTML内容,确保都被返回 content_tag("span", text, class: "b") + svg(icon) end end end
视图调用方式
在视图中直接调用该helper方法即可:
<%= primary_button(text: "SAVE", icon: "check-circle-solid") %>
可选拼接方式
如果需要处理更复杂的内容组合,也可以使用concat方法:
def primary_button(text:, icon:) button_tag type: "submit", class: "a" do concat(content_tag("span", text, class: "b")) concat(svg(icon)) end end
内容的提问来源于stack exchange,提问作者Sig
相关产品推荐
相关产品推荐

