[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)
Avoid making the same mistake twice: Lessons learned by a Plone developer/integrator.
from zope.component import queryUtility
from plone.i18n.normalizer.interfaces import IIDNormalizer
id = queryUtility(IIDNormalizer).normalize(title)
2 comments:
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)
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!')
Post a Comment