Created
August 21, 2013 14:16
-
-
Save berlotto/6295018 to your computer and use it in GitHub Desktop.
Slugify function to use in Flask (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_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
font: http://code.activestate.com/recipes/577257-slugify-make-a-string-usable-in-a-url-or-filename/