Created
October 2, 2012 19:06
-
-
Save jayliew/3822570 to your computer and use it in GitHub Desktop.
Django template filter: Add zero-width space to break up long strings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.template.defaultfilters import stringfilter | |
from django.utils.safestring import mark_safe | |
from django import template | |
register = template.Library() | |
@register.filter | |
@stringfilter | |
def zerowidthspace_separator(value, num): | |
""" | |
Add zero-width space every num chars in string | |
""" | |
num = int(num) | |
locations = range(0, len(value), num)[1:] # loc to insert | |
new_value = value[:num] | |
for loc in locations: | |
if loc + num < len(value): | |
new_value += '' + value[loc:(loc+num)] | |
else: | |
new_value += '' + value[loc:] # last substring may have less than num chars | |
return mark_safe(new_value) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment