Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在助手中混合HTML代码_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails 在助手中混合HTML代码

Ruby on rails 在助手中混合HTML代码,ruby-on-rails,ruby,Ruby On Rails,Ruby,但是,当我看到其他人使用的一些简化的Ruby代码时,下面的代码看起来非常笨拙 在助手中混合使用Ruby和HTML时,这是正确的编码方式吗 def display_children(children) if children.count == 0 "<p>No child records exist</p>".html_safe else s = "" s << "<table class='table table-bo

但是,当我看到其他人使用的一些简化的Ruby代码时,下面的代码看起来非常笨拙

在助手中混合使用Ruby和HTML时,这是正确的编码方式吗

def display_children(children)
  if children.count == 0
    "<p>No child records exist</p>".html_safe
  else  
    s = ""
    s << "<table class='table table-bordered text-center'>"
    children.in_groups_of(4) do |row_children|
      s << "<tr>"
      row_children.each do |child|
        s << "<td class='col-md-3'>"

        if child
          s << link_to(child.name, child)
        else
          s << '&nbsp;'
        end

        s << "</td>"
      end
      s << "</tr>"  
    end
    s << "</table>"
    s.html_safe
  end
end
def显示子项(子项)
如果children.count==0
“不存在子记录

”.html\u安全 其他的 s=“”
s简单的答案是从helper中删除所有代码并将其放在一个部分中


用于选择HTML输出的代码通常嵌入到HTML中。帮助程序用于运行更复杂的代码,如查询和准备要显示给用户的数据。

那么,帮助程序是否生成html或只是将原始数据返回到要显示为html的视图中?它不会“生成”html,但您可以让它像在代码中那样返回html。你想的是一个局部的。“product”部分,或者更优选地措辞为“render”,用于浏览器的HTML。当您在视图中调用帮助程序时,它只是调用一个常规方法/函数/子例程。没有什么特别的事情发生。请记住,您的方法位于帮助器模块中,而不是控制器类中。这篇文章应该有帮助: