$.fn.dataTable.render.text combine with render: function(data, type, row)?

$.fn.dataTable.render.text combine with render: function(data, type, row)?

shayhurstshayhurst Posts: 11Questions: 4Answers: 0

I have a requirement to safely output html and script, which I've learned I should use $.fn.dataTable.render.text() to achieve. Trouble is, I'm currently using render: function(data, type, row) and within that function I have some logic to decide what value to output. In most cases I'm simply rendering 'data' but in one case I'm rendering a different field in the row object.

How can I achieve safe rendering of html and script in this case? Here is my current function:

render: function(data, type, row){
    if(row.Type__c === 'Chat'){
        return row.Live_Chat_Transcript__r.Body;
    }else{
        return data;
    }
}

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,723Questions: 1Answers: 10,108 Site admin
    Answer ✓

    Use:

    var textRenderer = $.fn.dataTable.render.text().display;
    

    Then update your render function to be:

    render: function(data, type, row){
        if(row.Type__c === 'Chat'){
            return textRenderer( row.Live_Chat_Transcript__r.Body);
        }else{
            return textRenderer(data);
        }
    }
    

    Allan

  • shayhurstshayhurst Posts: 11Questions: 4Answers: 0

    Thanks that technically works. However we lose all line breaks making the text quite unreadable. I've noticed the line breaks are still in the DOM but not in the datatable, so I presume there's something that can be done to make sure they're still rendered in the table?

    Here is how it looks in the table:

    And here is how it looks in the inspector:

  • shayhurstshayhurst Posts: 11Questions: 4Answers: 0

    Ignore me, I'll just replace the line breaks in the resulting escaped string :smile: Thanks!

  • allanallan Posts: 61,723Questions: 1Answers: 10,108 Site admin

    Hah - yes, that's the problem with escaping HTML :).

    Allan

This discussion has been closed.