简体   繁体   中英

Rails Render Partial in Helper

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?

实际上,html_safe应该像这样使用: -

<%= display_replies(reply).html_safe %>

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!

您可以像这样使用html_safe方法

<%= html_safe display_replies(reply) %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM