Define/reuse a columns.render function

Define/reuse a columns.render function

sherpasherpa Posts: 2Questions: 1Answers: 0
edited November 24 in Free community support

preface: I am fairly new to Datatables.
I would like to define a columns.render function once and reuse it in multiple columns to eliminate code duplication, but I'm having difficulty with understanding where to put it in terms of scope or if it's possible at all. Ultimately, my goal is to build one large function that will append anchor tags based on the column name by using 'meta.settings.aoColumns[meta.col].mData'

I have tried defining a custom property (naming it renderFieldLinks) outside of columns and referencing it by that name as the value of the render key but I guess it's out of scope. I have also tried defining that in an object within columns, having created and additional <th> above so that the total columns match, then referring to that object by the index in the columns list, but it doesn't work and I would assume it's something to do with it not being referenceable at the time of instantiation of the Datatable itself.

Simply put, can someone please provide an example as to how I can define a columns.render function and pass it in to the value of 'render' in multiple columns.

Thanks!

This question has an accepted answers - jump to answer

Answers

  • rf1234rf1234 Posts: 2,448Questions: 78Answers: 353

    I just use a simple function. The function below return "Yes" or "No" in multiple languages depending on the user language. I use it many times for any kind of boolean field.

    columns: [
        { data: "yourBooleanField",
            render: function (data, type, row) {
                return renderBooleanYesNo(data);
            }
        },
    
  • kthorngrenkthorngren Posts: 17,294Questions: 25Answers: 4,109
    Answer ✓

    Probably the easiest option is to use columnDefs with a columnDefs.targets setting for the columns you want the columns.render function to run against.

    Its hard to say why your function doesn't work without seeing what you are doing. There is nothing special that needs to happen other than normal Javascript rules. Make sure to call the function with all the columns.render function parameters.

    You could create a data render plugin. See the examples.

    If you still need help please provide a link to your page or a test case replicating the issues so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

  • sherpasherpa Posts: 2Questions: 1Answers: 0

    kthorngren, you set me on the correct path. Thanks a bunch!

Sign In or Register to comment.