使用 Django tables 2,如何用省略号截断一个长文本字段?

Using Django tables 2, how do you cut off a long text field with an ellipsis?

我正在使用 django-tables2,并且我有一个文本很长的字段。

我想像这样截断:

这是一个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'

我试过这个关于 的答案,但它使所有行成为一行并且截断了太多。 我如何在代码中执行此操作?

您可以通过扩展 Column 并覆盖 render 方法来做到这一点:

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)

和用法:

comment = TruncatedTextColumn(accessor=A('Comment'))

我正在结合使用 truncatewords 和工具提示:

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