I find myself doing this all the time:
<% if !foo.blank? %>
Is there a better way?
Many thanks,
Rob
I find myself doing this all the time:
<% if !foo.blank? %>
Is there a better way?
Many thanks,
Rob
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. [email protected]
Using unless instead of if !foo might make it easier on the eyes.
<% unless foo.blank? %>
Shane
On 5/31/07, Robert H. [email protected] wrote:
Rob
–
Posted via http://www.ruby-forum.com/.
…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.
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.
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
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’
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.
Sponsor our Newsletter | Privacy Policy | Terms of Service | Remote Ruby Jobs