views:

139

answers:

3

I have this code

<% if approved %>
  <td>Flow Number</td>
<% end %>

and I'd like to shorten it using statement modifiers. Of course I can use

<%="<td>Flow Number</td>" if approved -%>

but is there a shorter way? I'd also like to get the markup out of quotes.

+4  A: 

You could use "content_tag", which isn't actually shorter, but may be more appealing, keeping HTML out of your ruby blocks:

<%= content_tag :td, "Flow Number" if approved %>

Otherwise, you could consider writing a helper - which may be appealing if you need to reuse similar logic throughout the page (or over several pages).

NeilS
Thanks for that, Neil. More options is/are what I'm looking for. I'll have to look into the content_tag a bit more. We use it to insert content from a page to a template, but not in the way you have it here. Might be nice.
Yar
Whoops, I meant we use content_for. I didn't know about content_tag, that's nice.
Yar
+2  A: 

Maybe HAML?

That'd be:

- if approved?
  %td Flow Number

Not exactly what you're after I know.

wombleton
Always interested in new stuff, even if I end up deciding it's junk. I'll check it out, thanks for that.
Yar
A: 

Yeah, I think a helper method using content_tag internally would be the best short way. Using a helper method, you could also yield to the desired output like this:

# in view helper
def show_if(condition, wrapper_tag)
  condition ? content_tag(wrapper_tag, yield) : ''
end

# in view
<%= show_if(approved, :td) {'Flow Number'} %>

or

# in view helper
def show_if(condition)
  condition ? yield : ''
end

# in view
<% show_if(approved) do %>
  <td>Flow Number</td>
<% end %>

I like this last method for a nice generic way to show or hide whole blocks based on a condition. Hope that helps!