Rails Render Partial in Helper

I am trying to map one of my partial functions to a helper function located inside my controller.

The first problem I ran into was that the helper returned every loop instead of the loop result. To fix this, I tried to 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 a view with <%= display_replies(reply) %>

When I look in my opinion, what is returned and displayed is HTML, however it is escaped and thus is 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 just wish it was plain unescaped HTML. I read somewhere that adding html_safe will fix this, but alas, this did not happen.

Where to go from here?

+4
source share
3 answers

Actually, html_safe should be used as follows: -

 <%= display_replies(reply).html_safe %> 
+6
source

To fix \n and [" , after the loop we must have .join . For example:

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) %>

Please note that I removed all html_safe and replaced it with raw . And instead of each loop, I used map , so we don’t need to create a string variable and return it after the loop.

Hope this helps!

+1
source

You can use html_safe method like this

 <%= html_safe display_replies(reply) %> 
0
source

Source: https://habr.com/ru/post/1502004/


All Articles