Skip to content

Instantly share code, notes, and snippets.

@ronbeltran
Forked from berlotto/app.py
Last active August 29, 2015 14:22
Show Gist options
  • Save ronbeltran/62a8759cd586779a7f78 to your computer and use it in GitHub Desktop.
Save ronbeltran/62a8759cd586779a7f78 to your computer and use it in GitHub Desktop.
_slugify_strip_re = re.compile(r'[^\w\s-]')
_slugify_hyphenate_re = re.compile(r'[-\s]+')
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
From Django's "django/template/defaultfilters.py".
"""
import unicodedata
if not isinstance(value, unicode):
value = unicode(value)
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(_slugify_strip_re.sub('', value).strip().lower())
return _slugify_hyphenate_re.sub('-', value)
@app.template_filter('slugify')
def _slugify(string):
if not string:
return ""
return slugify(string)
# then in your template use: {{myname|slugify}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment