4

I am using django-tables2 and I have a field that has really long text.

django-table2 long text

Which I would like to truncate like this:

django-table2 shortened text

It is a bootstrap table:

class EntryRecordTable(tables.Table):
    ...
    comment = tables.Column(accessor=A('Comment'))

    class Meta:
        template_name = 'django_tables2/bootstrap-responsive.html'
        attrs = {'class': 'table table-bordered'}
        orderable = False
        empty_text = 'No entries for selected dates'

I have tried this answer about truncating text in a bootstrap table, but it makes all rows a single line and truncates a bit too much. How can I do this in code?

tread
  • 10,133
  • 17
  • 95
  • 170

2 Answers2

7

I am using truncatewords combined with tooltip:

comment = tables.TemplateColumn('<data-toggle="tooltip" title="{{record.comment}}">{{record.comment|truncatewords:5}}')
flopezlira
  • 71
  • 2
  • 5
5

You can do this by extending Column and overriding the render method:

class TruncatedTextColumn(tables.Column):
    '''A Column to limit to 100 characters and add an ellipsis'''
    def render(self, value):
        if len(value) > 102:
            return value[0:99] + '...'
        return str(value)

and usage:

comment = TruncatedTextColumn(accessor=A('Comment'))
tread
  • 10,133
  • 17
  • 95
  • 170
  • This looks like a great solution. Where does this code go, though? – Evan Sep 18 '19 at 23:38
  • 1
    In `tables.py`....just add the class above then use it as a column in your table extended from `tables.Table` – tread Sep 19 '19 at 07:16
  • Cool, thanks! I spent a while looking for a solution, and this seems like the most efficient. – Evan Sep 19 '19 at 16:54
  • `text-overflow: ellipsis` is another option, https://developer.mozilla.org/en-US/docs/Web/CSS/text-overflow – tread Sep 19 '19 at 19:41