Rails Render Partial in Helper

2019-03-21 12:44发布

问题:

I have been trying to render one of my partials in a helper function located within my controller.

The first issue I encountered was that the helper was returning the each loop instead of the result of the loop. To remedy this I attempted to have it return a string containing the results of the loop.

def display_replies(comment)
    if comment.replies.count > 0
        string = ""
        comment.replies.each do |reply, index|
        string = string + (render partial: "comment", locals: {index: index}).to_s.html_safe
        end
        string
    end

Called in View with <%= display_replies(reply) %>

When I look at my view, what is returned and displayed is HTML, however it is escaped and thus plain text, it looks something like this:

["<div class='c comment'>\n<div class='profile'>\n<img src='/assets/profile_image_sample.jpg'>\n</div>\n<div class='message'>\n<div class='username'>Will Leach</div>\nLorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus adipiscing purus et mi aliquet malesuada. Curabitur porttitor varius turpis eget sollicitudin. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut dapibus consectetur tortor, nec aliquet lacus tempus vitae. Sed felis massa, dapibus in arcu sit amet, rhoncus condimentum eros. Etiam rutrum lectus in malesuada aliquam. Mauris vitae diam vel felis accumsan vulputate vel nec tortor. Nunc pretium hendrerit est, ut cursus ipsum commodo sit amet.\n<div class='reply-link'>\n<a href='#'>Reply to Comment</a>\n</div>\n</div>\n</div>\n"]

I would simply like this to be regular unescaped HTML. I read somewhere that adding html_safe would fix this, but alas it hasn't.

Where to go from here?

回答1:

Actually, html_safe should be used like this:-

<%= display_replies(reply).html_safe %>


回答2:

To fix \n and [", we need to have .join after the loop. Like so:

Helper:

def display_replies(comment)
  if comment.replies.count > 0
    raw(
      comment.replies.map do |reply, index|
        render 'comment', index: index
      end.join
    )
  end
end

View:

<%= display_replies(reply) %>

Note that I removed all html_safe and replaced with raw. And instead of each loop, I used map, so we don't have to create variable string and return it after the loop.

Hope this helps!



回答3:

You can use the html_safe method like this

<%= html_safe display_replies(reply) %>