Alert This post is over a year old, some of this information may be out of date.

Showing Alternating Rows in the Content Search WebPart (Display Template)

August 8, 2013

Showing alternating rows can be done in various ways, you can do it via jQuery or even with CSS. Another way is to add an alternating class to the item via the Item Display Control. I’ll explain the last method in this post.

Note: here are the references to the jQuery and CSS methods: jQuery Odd Selector - CSS Even and Odd

Let’s start

What do you need to create an alternating row class functionality? The only thing you really need is the current item index number.

Luckily this index number can be retrieved from the current context:

1
var currentItemIdx = ctx.CurrentItemIdx + 1;

Note: the +1 isn’t necessary, but I’ll use it in a later step to check the last item.

When you retrieved the index number, the next step is to check if it’s an even or odd number. This can be done by checking if the number is divisible by 2 (even numbers), if the condition is met, you can set the class name to a variable.

1
2
3
4
var altClass = "";
if (currentItemIdx % 2 === 0) {
  altClass = "alternative";
}

This variable can be used to be added to the class property of your HTML element like this:

1
<div class="cbs-Item _#= altClass =#_" id="_#= containerId =#_" data-displaytemplate="Item2Lines">

Now that you added the alternating class to the item row, you’ll need to do the styling in your CSS file.

Alternating rows
Alternating rows

Extra Information

Another useful property is the RowCount, so you can check if the last item is processed:

1
ctx.CurrentGroup.RowCount

Here is an example how to use it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<!--#_
if(currentItemIdx === ctx.CurrentGroup.RowCount) {
_#-->
  <div class="ms-noWrap">I'm the last row</div>
<!--#_
} else if (currentItemIdx === 1) {
_#-->
  <div class="ms-noWrap">I'm the first row</div>
<!--#_
}
_#-->
First row - Last row
First row - Last row

Comments

comments powered by Disqus