I have this helper method that I can’t seem to clean up with content_tag in Rails 3.1
def site_address(site)
html = '<address>'
html += site.address1 if site.address1.present?
html += tag(:br) + site.address2 if site.address2.present?
html += tag(:br) + site.city + ', ' if site.city.present?
html += site.state.statecode if site.state.present?
html += ' ' + site.zipcode if site.zipcode.present?
html += '</address>'
html.html_safe
end
If I try using content_tag(:address) do.... and then put the content in the block, it just escapes my <br /> tags.
Also notice there is a lot of if.present? logic because the table can have a bunch of null values.
Thanks
Have you considered moving this logic into a partial? Also, you should be using the new
#presencemethod.First, the method:
Then, the partial:
In general, using
html_safein a helper is a hint that you might be going overboard with HTML logic in your helper, and that it might a good idea to fall back on the template engine, which lets you more easily mix static and dynamic content with good default XSS-safe semantics.Note: If
address1,address2, etc. are actuallynil, and not possibly an empty String (I suspect this is true about site.state, at least), you don’t need to usepresentat all. Just sayif site.stateand call it a day. Thepresentandpresencemethods simply treat empty values as if they werenilfor the purpose of conditionals.