Code

Opened 3 years ago

Closed 2 years ago

#15307 closed New feature (wontfix)

slugify should take an optional max length

Reported by: jdunck 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.

Attachments (0)

Change History (4)

comment:1 Changed 3 years ago by Keryn Knight <keryn@…>

  • Component changed from Uncategorized to Template 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 Changed 3 years ago by jdunck

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 Changed 3 years ago by lrekucki

  • Severity set to Normal
  • Type set to New feature

comment:4 Changed 2 years ago by aaugustin

  • Easy pickings unset
  • Resolution set to wontfix
  • Status changed from new to closed
  • 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!

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.