Reputation: 37934
I am a bit stuck in this issue:
as we all know, django has a slugify
template tag which makes traume-von-bucher
out of Träume von Bücher
.
But syntactically, Träume
should become Traeume
which would be right german word.
How do I write my own custom tag so that Ä
will be slugified to Ae
?
Upvotes: 2
Views: 1420
Reputation: 5119
Just to add to the answer by beerbajay.
I wanted to change the default slugify for the whole application (the default implementation strips out the Norwegian characters 'ø' and 'æ') without having to fork/subclass everything just to modify the slugify call.
So I decided to monkeypatch it in. It should be safe to do so as long as the custom slugify is implemented like beerbajay example just doing some simple replacements and calling the original slugify; so that its output doesn't break any assumptions about it.
Here's how I did that (tested in Django 1.7 but it probably works in older versions too)
I created an app to contain the monkeypatching code, called monkeys
in this example.
Add it first in the installed apps so that it will run before all the other apps:
INSTALLED_APPS = (
'monkeys', # The monkey patches app
#... all the other apps below here
In the monkeys/__init__.py
file add this code:
import django.template.defaultfilters
from where.you.defined.it import custom_slugify
#print "MONKEY PATCHING NOW!"
#Uncomment the above to verify that this code actually called
django.template.defaultfilters.slugify = custom_slugify
As long all apps use the django.template.defaultfilters.slugify to make slugs this should work.
Upvotes: 1
Reputation: 20300
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.text import slugify
register = template.Library()
@register.filter
@stringfilter
def germanslugify(value):
replacements = [(u'ä', u'ae')]
for (s, r) in replacements:
value = value.replace(s, r)
return slugify(value)
Upvotes: 4