Django template tag to truncate text

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

    This has recently been added in Django 1.4. e.g.:

    {{ value|truncatechars:9 }}
    

    See doc here

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

    You should write a custom template filter: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#writing-custom-template-filters

    Have a look at how truncatewords is built in django.utils.text

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

    Here it is in the Django Documentation, Built-in template tags and filters: truncatechars

    0 讨论(0)
  • 2020-12-12 19:21
    {{ value|slice:"5" }}{% if value|length > 5 %}...{% endif %}
    

    Update

    Since version 1.4, Django have a built-in template tag for this:

    {{ value|truncatechars:9 }}
    
    0 讨论(0)
  • 2020-12-12 19:21

    If you prefer to create your own custom template tag, consider to use the Django util Truncator in it. The following is a sample usage:

    >>> from django.utils.text import Truncator
    >>> Truncator("Django template tag to truncate text")
    <Truncator: <function <lambda> at 0x10ff81b18>>
    >>>Truncator("Django template tag to truncate text").words(3)
    u'Django template tag...'
    Truncator("Django template tag to truncate text").words(1)
    u'Django...'
    Truncator("Django template tag to truncate text").chars(20)
    u'Django template t...'
    Truncator("Django template tag to truncate text").chars(10)
    u'Django ...'
    

    Then you can put it in a template tag:

    from django import template
    from django.utils.text import Truncator
    
    register = template.Library()
    
    @register.filter("custom_truncator")
    def custom_truncator(value, max_len, trunc_chars=True):
        truncator = Truncator(value)
        return truncator.chars(max_len) if trunc_chars else truncator.words(max_len)
    
    0 讨论(0)
  • 2020-12-12 19:25

    You can achieve your goal with similar code:

    {{ value_of_text|truncatechars:NUM_OF_CHARS_TO_TRUNCATE}}

    where NUM_OF_CHARS_TO_TRUNCATE is number of chars to leave.

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