Login

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

Author:
jayliew
Posted:
September 20, 2012
Language:
Python
Version:
1.4
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. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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.