1

I'm using JSLink to color code similar columns in a list view. I need set it up to color code 20+ columns, and the script I'm currently using seems a bit redundant. Is there a more optimized/less redundant way to write this for the additional 20+ columns? This is the script currently used to handle the first two fields:

(function () {
    var condFieldCtx = {};
    condFieldCtx.Templates = {};
    condFieldCtx.Templates.Fields = {
        "field1": {"View": colorCode1},
        "field2": {"View": colorCode2}
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(condFieldCtx);
})();

function colorCode1(ctx) {
    var ctxValue = ctx.CurrentItem.field1;

    if (ctxValue == 'TBD' || ctxValue.indexOf("N") !== -1 ) {
        return "<span style='background-color:#FFC107;'>" + ctxValue + "</span>";
    } else if (ctxValue == 'No') {
        return "<span style='background-color:#F44336;'>" + ctxValue + "</span>";
    } else if (ctxValue == 'Yes' || ctxValue.indexOf("Available") !== -1 ) {
        return "<span style='background-color:#4CAF50;'>" + ctxValue + "</span>";
    } else { return ctxValue; }
}

function colorCode2(ctx) {
    var ctxValue = ctx.CurrentItem.field2;

    if (ctxValue == 'TBD' || ctxValue.indexOf("N") !== -1 ) {
        return "<span style='background-color:#FFC107;'>" + ctxValue + "</span>";
    } else if (ctxValue == 'Deny') {
        return "<span style='background-color:#F44336;'>" + ctxValue + "</span>";
    } else if (ctxValue == 'Yes' || ctxValue.indexOf("Available") !== -1 ) {
        return "<span style='background-color:#4CAF50;'>" + ctxValue + "</span>";
    } else { return ctxValue; }
}

Thank you!

1 Answer 1

2

You could use ctx.CurrentItem[ctx.CurrentFieldSchema.Name] instead. See the code below:

function colorCode(ctx) {
 var ctxValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
 if (ctxValue == 'TBD' || ctxValue.indexOf("N") !== -1) {
    return "<span style='background-color:#FFC107;'>" + ctxValue + "</span>";
 } else if (ctxValue == 'No' || ctxValue == 'Deny') {
    return "<span style='background-color:#F44336;'>" + ctxValue + "</span>";
 } else if (ctxValue == 'Yes' || ctxValue.indexOf("Available") !== -1) {
    return "<span style='background-color:#4CAF50;'>" + ctxValue + "</span>";
 } else { return ctxValue; }
}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.