Creating your own tag helper in Rails

Lets say you get sick and tired of writing this in your views:

<div class="field">
  <%=form.label :location %>
  <%=form.text_field :location %>
</div>

and instead you would like to write

my_great_input_helper(form, "location")

how would you do it?

First you create a helper module. This could be named anything (as long as config.action_controller.include_all_helpers = true which is the default. If you turn it off (false) you will opnly have access to the helpers named after your own controller.  So UserHelpers module is available in UserController and User views, but TagHelper module is not.)

Heres my new TagHelper in app/helpers/tags_helper.rb:
module TagsHelper
  def my_great_input_helper(form, name)
    ("<div class='field'>" +
    form.label(name.to_s) +
    form.text_field(name.to_s) +
    "</div>").html_safe
  end
end
and now I can use it in my views:
<%=my_great_input_helper form, "adr1" %>
you can also use a symbol (since the helper converts it to a string with .to_s)
<%=my_great_input_helper form, :adr1 %>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.