Rails Way to display if !blank?


#1

I find myself doing this all the time:

<% if !foo.blank? %>

<%= foo %>
<% end %>

Is there a better way?

Many thanks,
Rob


#2

I know that in general it is a “good idea” to move logic out of
templates and into helpers when possible.

For example, you could create a helper (either in the particular
controller’s helper file or in the application’s helper file). Your
helper might be called “show_div” and it might accept the thing you
want to display as a parameter.

The helper would then test whether or not the object is empty and
display your output when the object is not empty.

Let me know if that is not enough detail. I can provide a working
example.

In any case, that’s what I have been doing in cases like this. There
may be other ways too. I’m looking forward to seeing what others
suggest.

On May 31, 6:18 pm, Robert H. removed_email_address@domain.invalid


#3

Using unless instead of if !foo might make it easier on the eyes.

<% unless foo.blank? %>

<%= foo %>
<% end %>

Shane

On 5/31/07, Robert H. removed_email_address@domain.invalid wrote:

Rob


Posted via http://www.ruby-forum.com/.


http://shanesbrain.net


#4

…and using content_tag (or elemental:
http://blog.dangosaur.us/elemental/) will let you golf it down to a
one-liner if you want.

<%= div(foo, :class => :foo_class) unless foo.blank? %>

~ j.


#5

Robert H. wrote:

<% if !foo.blank? %>

<%= foo %>
<% end %>

The elemental they mentioned in a previous message looks great. I have
also found this helper useful.

Will print the content in the given tag if the condition is true. If

no condition is provided then it will use the existance of real data

in the content value to determine if content should be printed

def if_tag(tag_name, content, html_options={},condition=!content.blank?)
content_tag(tag_name, content, html_options) if condition
end

I use would reproduce what you were trying to do with:

<%=if_tag(‘div’, foo, :class=>‘foo_class’)%>

Eric


#6

there is even more elegant solution using markaby.
by default markaby rendering empty tags, but you would easily change
its behaviour, look into builder.rb, search for tag! method and amend
it to return nothing if passed block converted to string is empty.
then all you need to write in in template is

div.foo_class ‘foo’