TAG | Zope3
2
Formatting and processing text in TAL templates
0 Comments | Posted by Ignas Mikalajūnas in Programming
Marius Gedminas wrote about a useful technique for formatting paragraphs — registering a view for “*” that does the processing for you.
While developing SchoolTool we
used a bit more complicated, but slightly more secure technique
— adapters implementing IPathAdapter.
To get the same effect that was described in Marius blog post you do this:
import cgi
from zope.interface import implements
from zope.traversing.interfaces import ITraversable
from zope.traversing.interfaces import IPathAdapter
from zope.component import adapts
class TalFiltersPathAdapter(object):
"""Collection of filters to be used in views for text processing."""
adapts(None)
implements(IPathAdapter, ITraversable)
def __init__(self, context):
self.context = context
def traverse(self, name, furtherPath=()):
handler = getattr(self, name)
return handler(furtherPath)
def paragraphs(self, furtherPath=()):
if self.context is None:
return ''
paras = filter(None, [s.strip() for s in self.context.splitlines()])
return "".join('<p>%s</p>\n' % cgi.escape(p)
for p in paras)
Register it like this:
<zope:adapter
for="*"
name="filter"
provides="zope.traversing.interfaces.IPathAdapter"
factory=".TalFiltersPathAdapter"
/>
And use it like this:
<p tal:replace="structure object/attribute/filter:paragraphs" />
The benefits of this technique – you don’t have
a zope.Public view registered on all your objects, it
will not “hog” ‘paragraphs’ view name (view names unless they are
registered for a specific skin are a shared resource) and you
can only access this functionality from TAL templates. The downside
— it is slightly more complicated and more TAL specific, so if
you are not using TAL templates you can’t really use this.

