Apologies for the noob question, but I can't seem to figure out how to return formatted HTML objects using a ruby enumerable and a helper. I want to remove the brackets. Is there anyway to return formatted objects with an enumerable based on an array of objects?
Helper
module PostsHelper
def display_posts(posts)
if posts.any?
raw(@posts.map {|p| raw("<div class='post_text_box'>#{p.body}</div>")})
end
end
end
HTML.erb
<div id="post_feed">
<%=display_posts(@posts)%>
</div>
Browser Output
It's recommended you do not join.html_safe
as the previous answer says, in rails due to the potential for injection attacks if your underlying strings aren't safe.
Use safe_join instead. It will maintain the "safeness" of the strings to output.
if posts.any?
safe_join( @posts.map {|p| "<div class='post_text_box'>#{p.body}</div>".html_safe } )
end
In your case I would make a partial named _post.html.erb containing
<div class='post_text_box'><%= post.body %></div>
and in your thing.html.erb file
<%= render @posts %>
Then Rails will automatically iterate @posts
over _post.html.erb
and join them for you.
This is all part of Rails's Convention over configuration, where if you render klass
, it first looks for _klass.<format>.<builder>
to render.