Thursday, June 9, 2011

How to plug into Plone's id (for url) generating mechanism

Plone can convert titles to id's, which are used in the URL. To use this conversion in your own code, use the IIDNormalizer utility.

[edit: removed broken link to Plone's developer documentation, added code snippet]


from zope.component import queryUtility
from plone.i18n.normalizer.interfaces import IIDNormalizer

id = queryUtility(IIDNormalizer).normalize(title)

2 comments:

Bas said...

I always use IUserPreferredURLNormalizer, since I saw Archetypes uses it:

# Import conditionally, so we don't introduce a hard dependency
try:
from plone.i18n.normalizer.interfaces import IUserPreferredURLNormalizer
from plone.i18n.normalizer.interfaces import IURLNormalizer
URL_NORMALIZER = True
except ImportError:
URL_NORMALIZER = False

# Following code is stolen from Archetypes' generateNewId method and adapted to our needs

# Make sure it's a unicode string before we continue
if not isinstance(txt, unicode):
txt = self._reencode(txt)

# Without the plone.i18n package, use normalizeString to at least generate some sort of id
if not URL_NORMALIZER:
return self.putils.normalizeString(txt)

request = getattr(self, 'REQUEST', None)
if request is not None:
return IUserPreferredURLNormalizer(request).normalize(txt)

return queryUtility(IURLNormalizer).normalize(txt)

David said...

This works, but only if you've got a context (within Zope, for instance) that the queryUtility will actually work. For working outside this, and just utilising the normalisation code:

from plone.i18n.normalizer import IDNormalizer
IDNormalizer().normalize('Give me an ID or give me death!')