Django Chinese character interception


It’s in DjangotruncatewordsandsliceTwo template filters can be used for character interception.truncatewordsChinese is not supported, so in general, Chinese characters are intercepted withsliceThat’s fine. But there are still differences between the two. For example, some developers mentioned the followingA little bit。 Then, there is the following solution. Put it here for backup.

The source of the following code is here, 2009 resources)

from django.template import Library
from django.template.defaultfilters import stringfilter 

register = Library() 

def truncatehanzi(value, arg):    
    Truncates a string after a certain number of words including    
    alphanumeric and CJK characters.     
    Argument: Number of words to truncate after.    
        bits = []
        for x in arg.split(u':'):
            if len(x) == 0:
        if int(x) < len(value):
            return value[slice(*bits)] + '...'
        return value[slice(*bits)]

    except (ValueError, TypeError):
        return value # Fail silently.
register.filter('truncatehanzi', truncatehanzi)

Recommended Today

Using stratis to manage local storage in centos8 (1)

Stratis is a new local storage management tool provided in rhel8 / centos8, which will help create tiered storage on block devices. In rhel8 / centos8, stratis can be obtained by installing two packages. In rhel7, we have Btrfs file system. Red hat removes Btrfs support in RHEL 8 and provides stratis local storage management […]