Filter to add zero-width space to break up long words

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 += '&#8203;' + value[loc:(loc+num)]
		else:
			new_value += '&#8203;' + value[loc:] # last substring may have less than num chars

	return mark_safe(new_value)

More like this

  1. wordbreak filter by soniiic 4 years, 1 month ago
  2. Wrappable text by jdunck 3 years, 7 months ago
  3. nbsp filter by vitamon 6 months, 2 weeks ago
  4. Avoid widows using a template filter by jcroft 6 years, 2 months ago
  5. Template context processor to make the settings.py values available in templates by tamizhgeek 2 years ago

Comments

(Forgotten your password?)