Never been to TextSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Wraps a block of content in an html tag, only if it has content present (See related posts)

Fed up of empty wrapper html tags when content isn't there? Then use this Rails helper...

  def tag_unless_empty(html_tag, options = {}, &block)
    html_options = options.stringify_keys

    if block_given?
      content = capture(&block)
      unless content.strip.empty?
        concat(tag(html_tag, html_options, true), block.binding)
        concat(content, block.binding)
        concat("#{html_tag}>", block.binding)
      end
    end
  end


Example:

<% tag_unless_empty :div, :class => "css_class" do %>
   <%# Nothing actually rendered here %>
   <%# or here %>
<% end %>


produces nothing, whereas

<% tag_unless_empty :div, :class => "css_class" do %>
   <%= 'Something rendered here' %>
<% end %>


produces

<div class="css_class">Something rendered herediv>


You need to create an account or log in to post comments to this site.


Related Posts