now available

now available
Want fresh tech tips in your inbox?

Yield a Block within Rails Helper Method with Multiple Content_tags Using Concat


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...

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.


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

Tagged w/ #block #concat #content_tag #dry #helpers #html #strings #views #wrapper #yieldprogramming

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app