Login

Soft hyphenation (­) template filter using PyHyphen

Author:
dokterbob
Posted:
April 16, 2009
Language:
Python
Version:
1.0
Tags:
typografy ­ pyhyphen hyphenation soft text filter template hyphen
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. Tags & filters for rendering search results by exogen 7 years, 5 months ago
  2. Using Pygments with reST by joshua 8 years, 6 months ago
  3. Support for {% macro %} tags in templates, version 2 by mludvig 8 years ago
  4. Querystring Builder - create urls with GET params by jibberia 4 years, 7 months ago
  5. convert plain text to html by limodou 8 years, 6 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.