在 ruby on rails 中创建自定义 html 助手
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3797040/
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
create custom html helpers in ruby on rails
提问by takayoshi
I've starting programming on ASP.NET MVC Framework a year ago. Recently. I've learning Ruby On Rails Framework There is "custom html helper" feature in ASP.NET MVC So I can create my own html helper
一年前我开始在 ASP.NET MVC 框架上编程。最近。我正在学习 Ruby On Rails 框架 ASP.NET MVC 中有“自定义 html 助手”功能,因此我可以创建自己的 html 助手
<%= Html.MyOwnHtmlHelper() %>
I've learned that there is html helpers in Ruby such as
我了解到 Ruby 中有 html 助手,例如
<% text_area %>
which render at html
以 html 呈现
I have a question. Can I create my own html helper for rendering my own html?
我有个问题。我可以创建自己的 html helper 来呈现我自己的 html 吗?
回答by Simone Carletti
To create a new helper:
创建一个新的助手:
- choose a name for the helper file, for instance tags_helper.rb
- create the file in the /app/helpers directory
create a module according to the file name. In this case
module TagsHelper enddefine your helper as method
module TagsHelper def hello_world(name) "hello #{name}" end end
- 为帮助文件选择一个名称,例如 tags_helper.rb
- 在 /app/helpers 目录中创建文件
根据文件名创建模块。在这种情况下
module TagsHelper end将您的助手定义为方法
module TagsHelper def hello_world(name) "hello #{name}" end end
Now you can use the hello_worldhelper method in your view.
现在您可以hello_world在视图中使用辅助方法。

