What's an elegant way to conditionally add a class to an HTML element in a view?

前端 未结 4 1861
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-07 13:33

I occasionally have to add a class to an html element based on a condition. The problem is I can\'t figure out a clean way of doing it. Here\'s an example of the stuff I\'ve

4条回答
  •  忘掉有多难
    2020-12-07 14:11

    I use the first way, but with a slightly more succinct syntax:

    Though usually you should represent success with boolean true or a numeric record ID, and failure with boolean false or nil. This way you can just test your variable:

    A second form using the ternary ?: operator is useful if you want to choose between two classes:

    Finally, you can use Rail's record tag helpers such as div_for, which will automagically set your ID and class based on the record you give it. Given a Person with id 47:

    # 
    <% div_for @person, class: (@success ? 'good' : 'bad') do %> <% end %>

提交回复
热议问题