Rails:如何将数组迭代从视图移动到帮助器(Rails: How to move array iteration from view to helper)

编程入门 行业动态 更新时间:2024-10-27 00:34:14
Rails:如何将数组迭代从视图移动到帮助器(Rails: How to move array iteration from view to helper)

我在视图中循环遍历数组,但是当我尝试将代码移动到辅助方法时,它无法正常工作。 问题是我无法在帮助器中执行<%=%>。 任何人都可以让我知道如何修复代码?

原始视图

<% resources.each do |resource| %> <span class="label label-primary"> <%= resource.name %> </span> <% end %>

更新的视图

<%= print_resource resources%>

resource_helper.rb

def print_resource(resources) resources.each do |resource| text = resource.name clz = 'label label-primary' content_tag :span, text,clz end end

I am looping through an array in view, it works, but when I tried to move the code to helper method, it did not work. The problem is I am not able to do <%= %> inside helper. Anybody could let me know how to fix the code?

original view

<% resources.each do |resource| %> <span class="label label-primary"> <%= resource.name %> </span> <% end %>

updated view

<%= print_resource resources%>

resource_helper.rb

def print_resource(resources) resources.each do |resource| text = resource.name clz = 'label label-primary' content_tag :span, text,clz end end

最满意答案

就这样做:

def print_resource(resources) html_values = "" resources.each do |resource| text = resource.name clz = 'label label-primary' html_values << (content_tag :span, text,clz) end html_values.html_safe end

Just do like this:

def print_resource(resources) html_values = "" resources.each do |resource| text = resource.name clz = 'label label-primary' html_values << (content_tag :span, text,clz) end html_values.html_safe end

更多推荐

本文发布于:2023-08-05 04:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1428244.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   视图   如何将   迭代   Rails

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!