To clean up some repetitive html coding in views, pass a block of text to a helper function which will wrap it for you the same way, each and every time. For example, I have a 'help' link which will toggle the display of a block of text if a link is clicked. I use this "+/- help" link throughout my application in various views. I could create a partial but this gets messy. Instead this is what I want to write in my views...
<% help do %> here is my help text... <% end %>which will render HTML similar to this...
<a href='#' 'class='help' id='help_link_123456' onclick='some_func_to_toggle_state'>+/- help</a> <div id="help_123456"> here is my help text... </div>
In order to accomplish this you need to create a helper method. Assigning a unique id, just a random number, will help avoid collisions with the state of the toggled div if you use this more than once per page. Placing other HTML helper methods inside the concat() method allows multiple tags as well as rendering the block passed to the function in the appropriate place. It looks a little unwieldy, but works nicely.
# app/helpers/application_helper.rb module ApplicationHelper def help(&block) uniqid = rand; concat( link_to_function("+/- help") do |page| page["help_#{uniqid}"].toggle page.visual_effect :highlight, "help_#{uniqid}" end + content_tag(:div,:class=>"help",:id=>"help_#{uniqid}", :style=>"display:none") do yield end ) end end
Just finishing up brewing up some fresh ground comments...