【问题标题】:Rails - How to avoid inserting the html in methodRails - 如何避免在方法中插入 html
【发布时间】:2020-04-19 04:25:30
【问题描述】:

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

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?有没有更优雅的方法来做到这一点?

【问题讨论】:

    标签: html ruby-on-rails ruby-on-rails-3


    【解决方案1】:

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

    您可以使用 rails 的 captureconcat 方法。比如:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-24
      • 2020-10-31
      • 2021-09-19
      • 1970-01-01
      • 2014-05-07
      • 2014-08-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多