Rails 查看助手文件中的助手 [英] Rails view helpers in helper file

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

问题描述

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

从这个角度来看,我正在调用一个自定义的辅助函数

<%=display_services%>

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

def display_serviceshtml = "

"form_for @user 做 |f|f.text_field ...结尾html <<</div>"结尾

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

解决方案

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

在您看来:

<% display_services %>

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

def display_servicesconcat("

")form_for @user 做 |f|f.text_field ...结尾concat("</div>")结尾

是否需要将

标签放入 helper 中.如果您需要帮助将某些内容嵌入到块中,您也可以使用一些 yield-magic:

def block_helperconcat("

")屈服concat("</div>")结尾

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

<% block_helper do %>冷块<br/><% display_services %><%结束%>

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

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.

解决方案

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:

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:

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 %>

这篇关于Rails 查看助手文件中的助手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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