Opened 14 years ago

Closed 13 years ago

Last modified 8 years ago

#15307 closed New feature (wontfix)

slugify should take an optional max length

Reported by: Jeremy Dunck Owned by: nobody
Component: Template system Version: 1.2
Severity: Normal Keywords:
Cc: Triage Stage: Design decision needed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

A SlugField has a max_length of 50 by default, but the slugify template filter does not easily truncate.

Perhaps altering to something like this would be helpful:

SLUG_RE = re.compile('\-[^\-]*$')
def slugify_max(text, max_length=50):
        slug = slugify(text)
        last_len = len(slug)
        while len(slug) > max_length:
            slug = SLUG_RE.sub('', slug)

            # avoid infinite loop
            if len(slug) == last_len:
                break
            last_len = len(slug)
        slug = slug[:max_length] #hack off end if unable to nicely crop it.
        return slug

Design decision needed because I'm not sure folks will agree this is needed in core.

Change History (5)

comment:1 by Keryn Knight <keryn@…>, 14 years ago

Component: UncategorizedTemplate system
  1. Would we really require an entirely separate filter to handle an 'optional' use case?
  2. Can the same functionality not be provided by {{ thing|slugify|slice:"N" }} ?

comment:2 by Jeremy Dunck, 14 years ago

1) No, I was just using it for illustrative purposes. It'd just be an optional to slugify.
2) Well, I'm trying to preserve word boundaries there, "this is an example headline" -> "this-example-headline" -> "this-example", not "this-example-he" if length were 15.

comment:3 by Łukasz Rekucki, 14 years ago

Severity: Normal
Type: New feature

comment:4 by Aymeric Augustin, 13 years ago

Easy pickings: unset
Resolution: wontfix
Status: newclosed
UI/UX: unset

Indeed, I'm not sure this belongs to core:

  • The relation to the max_length of SlugField isn't obvious to me — and if a form field was involved, a human would be better than a computer at shortening its contents while preserving its meaning.
  • It's easy to implement your idea as a custom template filter (I hope you've done so).
  • I'd prefer to keep slugify simple.

Thanks for the suggestion anyway!

comment:5 by Andrew Badr, 8 years ago

Here's a more efficient version of slugify_max, if anyone comes looking.

def slugify_max(text, max_length=50):
    slug = slugify(text)
    if len(slug) <= max_length:
        return slug
    trimmed_slug = slug[:max_length].rsplit('-', 1)[0]
    if len(trimmed_slug) <= max_length:
        return trimmed_slug
    # First word is > max_length chars, so we have to break it
    return slug[:max_length]

Note: See TracTickets for help on using tickets.
Back to Top