Ruby-on-rails Rails 查看助手文件中的助手

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1380938/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:42:51  来源:igfitidea点击:

Rails view helpers in helper file

ruby-on-rails

提问by Bob

I'm probably missing something obvious here but here's what I'm trying to do.

我可能在这里遗漏了一些明显的东西,但这就是我想要做的。

From the view, I'm calling a custom helper function

从视图上看,我正在调用自定义帮助函数

<div>
  <%=display_services%>
</div>

In the helper file with the display_services function

在带有 display_services 函数的帮助文件中

def display_services
  html = "<div>"
  form_for @user do |f|
   f.text_field ...
  end
 html << "</div>"
end

I find that form_for method and f.text_field output directly to HTML stream without the div wrapper that I like. What is the proper syntax to output all the HTML in display_services? Thanks in advance for your help.

我发现 form_for 方法和 f.text_field 直接输出到 HTML 流,而没有我喜欢的 div 包装器。在 display_services 中输出所有 HTML 的正确语法是什么?在此先感谢您的帮助。

回答by 0livier

IMHO, you should not have HTML hardcoded in Ruby code. Instead, prefer partials views.

恕我直言,你不应该在 Ruby 代码中硬编码 HTML。相反,更喜欢局部视图

module ServicesHelper
  def display_services(user)
    render :partial => "shared/display_services", :locals => {:user => user}
  end
end

回答by xijo

Just a suggestion for style, I like doing something like this:

只是对风格的建议,我喜欢做这样的事情:

In your view:

在您看来:

<% display_services %>

Please note that the =isn't needed any more. The helper then uses concat()to append something to your page and the putting-long-strings-together thing is obsolete too:

请注意,=不再需要 。然后,帮助程序concat()用于将某些内容附加到您的页面,并且将长字符串放在一起的内容也已过时:

def display_services
  concat("<div>")
  form_for @user do |f|
    f.text_field ...
  end
  concat("</div>")
end

Is it nessaccary to put the <div>tag into the helper. If you need a helper for embedding something into a block you could use some yield-magic as well:

<div>标签放入助手中是否必要。如果您需要帮助将某些内容嵌入到块中,您也可以使用一些 yield-magic:

def block_helper
  concat("<div>")
  yield
  concat("</div>")
end

And use it like this in your view - of course with helpers too:

并在您看来像这样使用它 - 当然也与助手一起使用:

<% block_helper do %>
  cool block<br/>
  <% display_services %>
<% end %>

回答by Bob

As it turns out, I had to do something like this

事实证明,我不得不做这样的事情

def display_services
  html = "<div>"
  html << (form_for @user do |f|
   f.text_field ...
  end)
  html << "</div>"
end

Note the () wrapped around the form block. If someone has a better solution, let me know.

注意包裹在表单块周围的 ()。如果有人有更好的解决方案,请告诉我。