帮助程序中的 Rails 渲染部分 [英] Rails Render Partial in Helper

查看:26
本文介绍了帮助程序中的 Rails 渲染部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在位于我的控制器内的辅助函数中呈现我的一个部分.

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

我遇到的第一个问题是 helper 返回的是 each 循环而不是循环的结果.为了解决这个问题,我试图让它返回一个包含循环结果的字符串.

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

在视图中调用 <%= display_replies(reply) %>

当我查看我的视图时,返回和显示的是 HTML,但是它被转义,因此是纯文本,它看起来像这样:

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"]

我只是希望这是常规的未转义 HTML.我在某处读到添加 html_safe 会解决这个问题,但可惜没有.

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.

从这里去哪里?

推荐答案

其实html_safe应该这样使用:-

Actually, html_safe should be used like this:-

<%= display_replies(reply).html_safe %>

这篇关于帮助程序中的 Rails 渲染部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆