请解释这段haml代码/文档(Please explain this snippet of haml code/documentation) %div{:class => [@item.type, @item == @sortcol && [:sort, @sortdir]] } Contents

可以渲染为以下任何一个:

<div class="numeric sort ascending">Contents</div> <div class="numeric">Contents</div> <div class="sort descending">Contents</div> <div>Contents</div>

我真的不明白这个片段的@sortcol && [:sort, @sortdir]部分。

%div{:class => [@item.type, @item == @sortcol && [:sort, @sortdir]] } Contents

could render as any of:

<div class="numeric sort ascending">Contents</div> <div class="numeric">Contents</div> <div class="sort descending">Contents</div> <div>Contents</div>

I don't really understand the @sortcol && [:sort, @sortdir] part of this snippet.

最满意答案

这依赖于运算符优先级。 所以评估如下:

@item == @sortcol是真还是假。 什么时候false &&返回false因为未评估其他部分 因此代码:class => [@item.type]为:class => [@item.type] 什么时候true &&返回表达式的第二部分。 在这种情况下数组[:sort, @sortdir] HAML在渲染之前自动展平数组,因此它等效于:class => [@item.type, :sort, @sortdir]

This relies on operator precedence. So it is evaluated like this:

@item == @sortcol is either true or false. when false && returns false because the other part is not evaluated hence the code reduces to :class => [@item.type] when true && returns the second part of the expression. In this case the array [:sort, @sortdir] HAML automatically flattens the array before rendering thus it's equivalent to :class => [@item.type, :sort, @sortdir]

更多推荐