Django template tag to truncate text

前端 未结 9 1802
长情又很酷
长情又很酷 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
    

提交回复
热议问题