Skip to content

Instantly share code, notes, and snippets.

@berlotto
Created August 21, 2013 14:16
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save berlotto/6295018 to your computer and use it in GitHub Desktop.
Save berlotto/6295018 to your computer and use it in GitHub Desktop.
Slugify function to use in Flask (Python)
_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