Login

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

Author:
jayliew
Posted:
September 20, 2012
Language:
Python
Version:
1.4
Tags:
word-break char-break wordbreak long-lines break wrap long-words wordwrap
Score:
0 (after 0 ratings)

If you have long words (no spaces) that are so long that it's messing up your design, add a 0-width space in the word every X chars.

Usage:

Step 1. Inside your app's directory, create dir called 'templatetags'. In that directory, create a .py file (say 'app_extras.py'). Make sure you make this a python module, make an empty the init .py (with the 2 underscores on each side).

Step 2. Inside template (make sure app is on INSTALLED_APPS list in settings.py):

{% load app_extras %}

Step 3. Enjoy!

{{ some_long_word_with_no_breaks|zerowidthspace_separator:25 }}

 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. Wrappable text by jdunck 5 years, 11 months ago
  2. Truncate text to length up until the nearest space by phektus 4 years, 5 months ago
  3. One step up from __icontains by peterbe 4 years, 11 months ago
  4. Super User Conditional Page Exception Reporting by zbyte64 7 years ago
  5. Currency Fields with newforms by sago 8 years, 4 months ago

Comments

kimyung (on July 14, 2013):

thx for this code its very help me cara jitu cepat hamil

#

Please login first before commenting.