rails slim 動態 body attributes 範例 (利用 content_for)

利用 rails template 中的 content_for 在 slim 中實做動態 body_attributes

MarsMars閱讀 2 分鐘
rails slim 動態 body attributes 範例 (利用 content_for)
application_helper.rb
def html_body_attributes
  content_for?(:body_attributes) ? ::Nokogiri::XML("<x>#{content_for(:body_attributes)}</x>").xpath('//x').first.children.each_with_object({}) { |node, obj| obj[node.name] = node.text } : {}
end

application.html.slim
body class=(yield :body_classes) *html_body_attributes
class=(yield :body_classes) 的部份可以忽略,因為我個人會把 <body> class 獨立出來用別的方式給值。

view 裡面使用方法
- content_for(:body_attributes) do
  data-turbolinks="false"
  data-lazy-loading="true"
每個 attribute 之間需要換行,slim 會以 xml 格式輸出,helper 中再 parse XML 以 ruby hash 輸出即可。
Mars
關於作者Mars自由接案工程師 | Ruby on Rails

自由接案者、Ruby on Rails 工程師、水肺潛水員、業餘羽球、二胡、鋼琴愛好者。喜歡貓、狗。

延伸閱讀