How to avoid writing same code twice on a dynamic websocket site in django templates and javascript?

In a django project, templates are used on the backend which render html that is displayed on the page. But when dealing with Channels (websockets) which receive 'notifications' from the server, I find that I have to re-write code in javascript to render the same html elements.

As an example, I started out with a HTML table element that in a django template page:

    {% for t in tickets %}
    <tr class="ticket-row">
        <td>{{ t.id }}</td>
        <td>
            <a href="/tickets/{{ t.id }}">
                {{ t.subject }}
            </a>
        </td>
        <td>
            <a href="/users/{{ t.user.id }}">
                {{ t.user.name}}
            </a>
        </td>
        <td class="tooltipped" data-tooltip="{{ t.date_time_updated }}">
            {{ t.date_time_updated|naturaltime }}
        </td>
        <td class="tooltipped" data-tooltip="{{ t.date_time_created }}">
            {{ t.date_time_created|naturaltime }}
        </td>
        ....

When channels receives a notification in javascript, I want to insert another row to the table without refresh, so I write JS code to do so like this:

function insertTicketRow(ticket) {
    document.getElementById("results").innerHTML = "Server: " + data.subject;
    var table = document.getElementById('ticket_table');
    var row = table.insertRow(1);
    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
    var cellId = row.insertCell(0);
    var cellSubject = row.insertCell(1);
    var cellFrom = row.insertCell(2);
        cellId.innerHTML = data.id;
    cellSubject.innerHTML = linkElement("/tickets/" + data.id, data.subject);
    cellFrom.innerHTML = linkElement("/users/" + data.user, data.author_name);
    cellLastUpdated.innerHTML = data.date_time_updated;
    cellCreatedOn.innerHTML = data.date_time_created;
    ....
}

Obviously this is not maintainable and I suspect the worst approach possible. What if I have 30 columns and not just a few? What about the attributes? Adding all this via javascript is doing the same work twice, AND, I have to put in extra logic to make the rendered HTML in javascript look the same like django's.

The question is, is there some method I can use to not write the same thing twice, but still be able to work with websockets and add elements to the page dynamically?

Back to Top