Fendo
Fendo

Reputation: 339

Please explain this snippet of haml code/documentation

%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.

Upvotes: 4

Views: 403

Answers (2)

Jakub Hampl
Jakub Hampl

Reputation: 40543

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

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

Upvotes: 4

fl00r
fl00r

Reputation: 83680

[@item.type, @item == @sortcol && [:sort, @sortdir]]
=>
# if @item.type is blank, so class is still empty
# if @item.type is "numeric" class is "numeric"
class = @item.type

# if @item equal @sortcol
# class will append "sort" and @sortdir if it is not empty.
if @item == @sortcol
  class += "sort"
  class += @sortdir
end

This construction @item == @sortcol && [:sort, @sortdir] will return [:sort, @sortdir] only if @item == @sortcol is true

Upvotes: 1

Related Questions