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 endI 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 endJust 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更多推荐
发布评论