首页 > 解决方案 > Rails - 如何避免在方法中插入 html

问题描述

我的项目中有一个方法可以在表格中显示书籍的标题和跟随的图标。方法是:

def title_and_follow()
  "#{h.link_to object.title, h.show_book_path(object.uuid)}
   #{h.follow_icon(user, object)}".html_safe
end

它工作正常,它在我的表中显示类似“Harry Potter [followed_icon]”的内容。但是,我想知道有没有什么办法可以避免在方法中直接插入 HTML?有没有更优雅的方法来做到这一点?

标签: htmlruby-on-railsruby-on-rails-3

解决方案


你的意思是不使用字符串插值然后.html_safe

您可以使用 railscaptureconcat方法。就像是:

def title_and_follow
  capture do
    concat link_to(object.title, show_book_path(object.uuid))
    concat follow_icon(user, object)
  end
end

我认为这应该是一个视图辅助方法(现在它看起来像是在其他地方,不确定,不清楚但h.对我来说看起来很奇怪)


推荐阅读