Rails views: how to prevent empty HTML tags from being output? -


often times in html have output e.g. list of links this:

/ note: slim template! ul   - if can? :edit, user     li create   - if can? :destroy, user     li destroy 

this leads empty ul tags being output when both can?s return false. what's common pattern prevent this? thing can think of following:

- if edit = can?(:edit, user) && destroy = can?(:destroy, user)   ul     - if edit       li create     - if destroy       li destroy 

but looks clumsy me. better idea?

first of all, i'm amazed see people preferring slim on haml. slim on erb , haml.

secondly, think code:

- if edit = can?(:edit, user) && destroy = can?(:destroy, user)   ul     - if edit       li create     - if destroy       li destroy 

will not output ul if there either edit or destroy false.

in such conditions, prefer use helper methods(because move logic there , keep views clean):

module applicationhelper   def show_content_for(user)     contents = []     contents << "create" if can? :edit, user     contents << "destroy" if can? :destroy, user     content_tag :ul       contents.collect { |content| concat(content_tag(:li, content)) }     end unless contents.blank?   end end 

in slim view:

= show_content_for user 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -