Soft hyphenation (­) template filter using PyHyphen

 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 3 years, 10 months ago
  2. Support for {% macro %} tags in templates, version 2 by mludvig 4 years, 6 months ago
  3. Using Pygments with reST by joshua 4 years, 11 months ago
  4. pygments stylize by mgiger 4 years, 6 months ago
  5. Querystring Builder - create urls with GET params by jibberia 1 year 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?

#

(Forgotten your password?)