#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 , 14 years ago
Component: | Uncategorized → Template system |
---|
comment:2 by , 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 , 14 years ago
Severity: | → Normal |
---|---|
Type: | → New feature |
comment:4 by , 13 years ago
Easy pickings: | unset |
---|---|
Resolution: | → wontfix |
Status: | new → closed |
UI/UX: | unset |
Indeed, I'm not sure this belongs to core:
- The relation to the
max_length
ofSlugField
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 , 9 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]
{{ thing|slugify|slice:"N" }}
?