Can I add an if-construction while rendering?

Can I add an if-construction while rendering?

arie0512arie0512 Posts: 16Questions: 5Answers: 0

I see some options for adding an If construction while rendering, see https://datatables.net/manual/data/renderers

But I can't figured it out how to add this one. I have now this render:

columns: [                
    { data: null, render: (data) => data.client.gender + ' ' + data.client.firstname + ' ' + data.client.lastname
    }
]

If the records hold this data:
Gender Firstname Lastname
M John Doe

Than I would like to have in the column Mister John Doe.

How to add the if-contruction into the render?

I have try to add ... => if (data.client.gender === 'M') { return Mister } but I get an error for using 'if'

Any idea how to achieve this?

Best regards,

Arie

Answers

  • allanallan Posts: 65,347Questions: 1Answers: 10,841 Site admin

    Hi Aire,

    You sure can, but your Javascript synax for the arrow function is slightly wrong. You need brackets around the function:

    render: (data) => {
      if (...) {
        return a;
      }
      return b;
    }
    

    For more details on the Javascript syntax for arrow functions, the MDN reference is excellent.

    Allan

  • kthorngrenkthorngren Posts: 22,329Questions: 26Answers: 5,135

    but I get an error for using 'if'

    Looks like you need to place quotes around Mister like this:

    => if (data.client.gender === 'M') { return "Mister" }
    

    If this doesn't help then please provide a link to a test case so we can see exactly what you have and the error you are getting so we can help debug.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

Sign In or Register to comment.