Rails用content_tag產生html


一般我們會在helper當中利用content_tag撰寫html,以減少我們在view當中有過多的html code。

content_tag(:h2, "A Title")
# => <h2>A Title</h2>

除此之外,也可以加上其他屬性。

content_tag(:p, "This is bold", :class => "bold", :style => "font-weight: bold")
# => <p class="bold" style="font-weight:bold">This is bold</p>

另外也可以用nesting的方式,用其他content_tag包在裡頭。

content_tag(:p, content_tag(:span, "this is span"), :style => "color: red")
# => <p>
# =>   <span>this is span</span>
# => </p>

content_tag :div, :class => "container" do
  content_tag(:h2, "This is title") +
  content_tag(:p, "This is content") +
  "Footer"
end
# => <div>
# =>   <h2>This is title</h2>
# =>   <p>This is content</p>
# =>   "Footer"
# => </div>

要注意到在block當中,每個content_tag必須用+號連接,而也可以連接一般字串,這樣的用法在select也很適合使用。

當然,過於複雜的html內容,還是直接另外包成partial較好。

參考資料

Ruby on Rails api

圖片來源

WikiMedia