https://www.codeproject.com/Articles/620110/%2FArticles%2F620110%2FSharePoint-Client-Side-Rendering-List-Views
Example: Color coding
Let's consider a more real-world example - color coding. So for example, I want to paint green all rows from a document library that have status "Approved".
Since there's not much of a customization here - I need just to change a css property of an existing element, - best way to accomplish this would be to use OnPostRender event and manipulate DOM elements that were rendered by CSR.
From OnPostRender, the ctx is accessible, thus it is not a problem to determine which documents were approved (given the Approved column is included into the view). The only tricky thing is to get the ID of the element that represents the row. Here I cheated a bit, by peeking into the CSR guts and finding a function, that generates row ids (but obviously, you can also figure out these IDs from the page source and generate them manually).
Now everything is simple: we have the element IDs, and we can acquire field values from ctx (after a short investigation I found them in the ctx.ListData.Row array).
So here's the final code:
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
OnPostRender: function(ctx) {
var rows = ctx.ListData.Row;
for (var i=0;i<rows.length;i++)
{
var isApproved = rows[i]["_ModerationStatus"] == "Approved";
if (isApproved)
{
var rowElementId = GenerateIIDForListItem(ctx, rows[i]);
var tr = document.getElementById(rowElementId);
tr.style.backgroundColor = "#ada";
}
}
}
});
This will work for English portal, but better make it international. For that, you need to replace "_ModerationStatus" with "_ModerationStatus." (dot at the end!), and compare with 0.
0 is for Approved
3 is for Draft
In short
var isDraft =rows[i]["_ModerationStatus."] == "3"; //_ModerationStatus. Draft is 3 Approved is 0
if (isDraft)
{
//backgroundColor...
}