Django template tag to truncate text

前端 未结 9 1754
长情又很酷
长情又很酷 2020-12-12 18:40

Django has truncatewords template tag, which cuts the text at the given word count. But there is nothing like truncatechars.

What\'s the best w

相关标签:
9条回答
  • 2020-12-12 19:28

    I made my own template filter, that add "..." to the end of (last word of) the (truncated) string as well:

    from django import template
    register = template.Library()
    
    @register.filter("truncate_chars")
    def truncate_chars(value, max_length):
        if len(value) > max_length:
            truncd_val = value[:max_length]
            if not len(value) == max_length+1 and value[max_length+1] != " ":
                truncd_val = truncd_val[:truncd_val.rfind(" ")]
            return  truncd_val + "..."
        return value
    
    0 讨论(0)
  • 2020-12-12 19:29

    slice

    0 讨论(0)
  • 2020-12-12 19:29

    Adding a "truncate" filter was a feature request for 4 years but finally landed in trunk, as far as I understand https://code.djangoproject.com/ticket/5025 - so we’ve to wait for the next release or use trunk.

    0 讨论(0)
提交回复
热议问题