Login

Soft hyphenation (­) template filter using PyHyphen

Author:
dokterbob
Posted:
April 16, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

soniiic (on April 22, 2009):

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.