有条件地将类添加到视图中的 HTML 元素的优雅方式是什么? [英] What's an elegant way to conditionally add a class to an HTML element in a view?
问题描述
我有时必须根据条件向 html 元素添加一个类.问题是我想不出一个干净的方法来做到这一点.这是我尝试过的东西的一个例子:
或
<% if @status == 'success' %><%其他%><div><%结束%>这里有一些消息
我不喜欢第一种方法,因为它看起来很拥挤且难以阅读.我不喜欢第二种方法,因为嵌套被搞砸了.将它放在模型中会很好,(类似于 @status.css_class
),但这不属于那里.大多数人做什么?
解决方案 我使用第一种方式,但语法稍微简洁一些:
<div class="<%= 'ok' if @status == 'success' %>">
虽然通常你应该用布尔值 true
或数字记录 ID 表示成功,用布尔值 false
或 nil
表示失败.这样你就可以测试你的变量:
如果您想在两个类之间进行选择,则使用三元 ?:
运算符的第二种形式很有用:
<div class="<%= @success ? 'good' : 'bad' %>">
最后,您可以使用 Rail 的 记录标签助手,例如 div_for
,它将根据您提供的记录自动设置您的 ID 和类.给定一个 id 为 47 的 Person
:
# <% div_for @person, class: (@success ? 'good' : 'bad') do %><%结束%>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 tried:
<div <%= if @status = 'success'; "class='ok'"; end %>>
some message here
</div>
OR
<% if @status == 'success' %>
<div class='success'>
<% else %>
<div>
<% end %>
some message here
</div>
I don't like the first approach because it's crowded looking and hard to read. I don't like the second approach because the nesting is screwed up. It'd be nice to put it in the model, (something like @status.css_class
), but that doesn't belong there. What do most people do?
解决方案 I use the first way, but with a slightly more succinct syntax:
<div class="<%= 'ok' if @status == 'success' %>">
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:
<div class="<%= 'ok' if @success %>">
A second form using the ternary ?:
operator is useful if you want to choose between two classes:
<div class="<%= @success ? 'good' : 'bad' %>">
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 id="person_47" class="person good">
<% div_for @person, class: (@success ? 'good' : 'bad') do %>
<% end %>
这篇关于有条件地将类添加到视图中的 HTML 元素的优雅方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文