简体   繁体   English

Rails在Helper中渲染部分

[英]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) %> 在View中调用<%= 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: 当我查看我的视图时,返回并显示的内容是HTML,但它是转义的,因此是纯文本,它看起来像这样:

["<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. 我只是想这是常规的非转义HTML。 I read somewhere that adding html_safe would fix this, but alas it hasn't. 我在某处读到添加html_safe会解决这个问题,但唉它没有。

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: 要修复\\n[" ,我们需要在循环之后使用.join 。就像这样:

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 . 请注意,我删除了所有html_safe并替换为raw And instead of each loop, I used map , so we don't have to create variable string and return it after the loop. 而不是each循环,我使用map ,所以我们不必创建变量string并在循环后返回它。

Hope this helps! 希望这可以帮助!

您可以像这样使用html_safe方法

<%= html_safe display_replies(reply) %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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