Login

Slugify alternative

Author:
exogen
Posted:
April 10, 2007
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

I prefer to use this slugification function rather than the one included with Django. It uses underscores instead of dashes for spaces, and allows dashes and periods to occur normally in the string. I decided on this when considering reasonable slugified titles such as...

object-relational_mapper_2.5
ten_reasons_web-2.0_rocks
django-trunk_0.99_updated
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
from django import template
import re

register = template.Library()

@register.filter
def slugify(string):
    string = re.sub('\s+', '_', string)
    string = re.sub('[^\w.-]', '', string)
    return string.strip('_.- ').lower()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 3 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

ericmoritz (on July 3, 2008):

From what I hear dashes are supposed to be more search engine friendly. According the a Search Engine guy I know, the search engines equate a underscore to be an non-char. So school_closes_due_to_health_issues turns into schoolclosesduetohealthissues.

I take that stuff with a grain of salt though... I think the folks at Google are smart enough to realize folks use underscores as spaces in slugs.

Donno.

#

Please login first before commenting.