Rails - conditional html attributes

Looking back at the documents, I do not see the right way for this. Here is an example of using non-refactored code:

= link_to user.name, user, :meta => "#{user.public? ? '' : 'nofollow noindex'}" 

Now it can be the same with any html attribute, the result is that I do not have a valid xhmtl due to an empty tag in the absence of an event.

 <a href='/users/mark' meta=''>Mark</a> 

How can I make an attribute definition conditional, and not just its value.

+7
source share
2 answers

Use nil instead of the empty string:

= link_to user.name, user, :meta => user.public? ? nil : 'nofollow noindex'

+18
source

This question has been answered, but I would like to mention a special case in which the drasbo method drasbo not work.

If you want the attribute to be conditional. Say the verified attribute input[type=checkbox] !

Having a verified attribute makes a difference, and unfortunately browsers tend to ignore its value.

Unfortunately, its not available with HAML syntax. To do this, you need to return to the standard HTML tag:

 %form <input type="checkbox" "#{@post.tags.include?("Special Blog")? "checked" : ""}" /> %button Click Me 
+4
source

All Articles