DRY and Export Titles

DRY and Export Titles

rdmrdm Posts: 194Questions: 55Answers: 4

I'm looking at the "title" examples on https://datatables.net/extensions/buttons/examples/html5/titleMessage.html. Suppose I want to apply the same title to both Excel and Print buttons. Following the example on the page, I developed this. While it works as intended, I notice that I'm repeating the same title in both extensions. While this is a very small example, suppose we scaled this up to many functions across many pages. That's a lot of extra typing. Is there a Data Tables way to apply the same title to all declared buttons? (In this case, excelHtml5 and print).

const date = new Date();
const dateStamp = moment(date).format("YYYY-MM-DD");

const enrollmentHistory = $("#EnrollmentHistory").DataTable({
    dom: "lBfiprt",
    buttons: [
        {
            extend:"excelHtml5",
            title:`${dateStamp} Schoolmaster FY20 Enrollment History`
        }, 
        {
            extend:"print",
            title:`${dateStamp} Schoolmaster FY20 Enrollment History`
        }]
});

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,489Questions: 1Answers: 10,470 Site admin
    Answer ✓

    The shortest would be to save it to a variable:

    var title = `${dateStamp} Schoolmaster FY20 Enrollment History`;
    
    // ... then
            {
                extend:"excelHtml5",
                title: title
            },
    

    The other option would be to use $.extend() (or Object.assign() if you prefer):

    buttons: [
      $.extend( { extend: 'excelHtml5' }, common ),
      $.extend( { extend: 'print' }, common )
    ]
    

    where common is just { title: ...}.

    Allan

  • rdmrdm Posts: 194Questions: 55Answers: 4

    Now it looks obvious. Thanks. :)

This discussion has been closed.