This template filter is meant to insert soft hyphens (­ entities) in text whever it can. For this is relies on a recent checkout of the PyHyphen interface to the hyphen-2.3 C library, which is also used by Mozilla and OpenOffice.org.
It takes two optional parameters: the language to hyphenate in and the minimum word length to consider for hyphenation. If no language is given, the default language from the settings file is used. The second parameter defaults to 5 characters.
Usage example:
{% load hyphenation %}
{{ object.text|hyphenate:"nl-nl,6" }}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | from hyphen import hyphenator, dictools
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
from django import template
register = template.Library()
from django.conf import settings
@register.filter
def hyphenate(value, arg=None, autoescape=None):
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
if arg:
args = arg.split(u',')
code = args[0]
if len(args) > 1:
minlen = int(args[1])
else:
minlen = 5
else:
code = settings.LANGUAGE_CODE
s = code.split(u'-')
lang = s[0].lower() + u'_' + s[1].upper()
if not dictools.is_installed(lang):
dictools.install(lang)
h = hyphenator(lang)
new = []
for word in value.split(u' '):
if len(word) > minlen and word.isalpha():
new.append(u'­'.join(h.syllables(word)))
else:
new.append(word)
result = u' '.join(new)
return mark_safe(result)
hyphenate.needs_autoescape = True
|
More like this
- Add custom fields to the built-in Group model by jmoppel 1 month, 2 weeks ago
- Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 5 months ago
- Python Django CRUD Example Tutorial by tuts_station 5 months, 2 weeks ago
- Browser-native date input field by kytta 7 months ago
- Generate and render HTML Table by LLyaudet 7 months, 1 week ago
Comments
You're setting 'esc' and then not using it. You're escaping at the very end, won't that try to escape the ampersand and make the shy not work?
#
Please login first before commenting.