OPEN TO WORK

Available for new opportunities! Let's build something amazing together.

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

Display Templates Search
post

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

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:

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.

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:

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

Show image Alternating rows
Alternating rows

Extra Information

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

ctx.CurrentGroup.RowCount

Here is an example how to use it:

<!--#_
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>
<!--#_
}
_#-->
Show image First row - Last row
First row - Last row

Related articles

Report issues or make changes on GitHub

Found a typo or issue in this article? Visit the GitHub repository to make changes or submit a bug report.

Comments

Elio Struyf

Solutions Architect & Developer Expert

Loading...

Let's build together

Manage content in VS Code

Present from VS Code