44

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

<%= Html.MyOwnHtmlHelper() %>

I've learned that there is html helpers in Ruby such as

<% text_area %>

which render at html

I have a question. Can I create my own html helper for rendering my own html?

1 Answer 1

66

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
    

Now you can use the hello_world helper method in your view.

Sign up to request clarification or add additional context in comments.

2 Comments

Does an HTML helper have to be a Module? Can it be a class?
I know this is old but: to use the built in rails mechanism and have it be automatically available, it has to be a module in the helper folder and possibly named correctly. You could use a plain old ruby object (a class) - and then you just have to call it with its full name and <%=HelloWorldHelper.new.hello_world_tag%> but the Helper mechanism is simpler and is a convention, and you would just call <%=hello_world_tag%>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.