开发者

Rails - conditional html attributes

开发者 https://www.devze.com 2023-01-31 18:34 出处:网络
Looking around the docs I cannot see a correct way to go about this. Here\'s an example using un-refactored code:

Looking around the docs I cannot see a correct way to go about this. Here's an example using un-refactored code:

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

Now this could be the same with any html attribute the result being I don't have valid xhmtl due to empty tag i开发者_JAVA百科n the case of the condition not passing.

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

How can I make the attribute definition conditional, not just it's value.


Use nil instead of an empty string:

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


This question is answered, but I would like to mention a special case in which drasbo's way wouldn't work.

If you want to make the presence of attribute conditional. Say checked attribute of input[type=checkbox]!

The presence of checked attribute makes the difference and sadly browsers tend to ignore its value.

Unfortunately, its not available with HAML syntax. To do that, you need to fallback to standard HTML tag:

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


This is an old question, but I've been doing this like this (Example taken from Annie's answer):

<input type="checkbox" <% :checked if @post.tags.include?("Special Blog") %> />
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号