在 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

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

create custom html helpers in ruby on rails

ruby-on-railsruby

提问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:

创建一个新的助手:

  1. choose a name for the helper file, for instance tags_helper.rb
  2. create the file in the /app/helpers directory
  3. create a module according to the file name. In this case

    module TagsHelper
    end
    
  4. define your helper as method

    module TagsHelper
      def hello_world(name)
        "hello #{name}"
      end
    end
    
  1. 为帮助文件选择一个名称,例如 tags_helper.rb
  2. 在 /app/helpers 目录中创建文件
  3. 根据文件名创建模块。在这种情况下

    module TagsHelper
    end
    
  4. 将您的助手定义为方法

    module TagsHelper
      def hello_world(name)
        "hello #{name}"
      end
    end
    

Now you can use the hello_worldhelper method in your view.

现在您可以hello_world在视图中使用辅助方法。