[ZPT] Truncating strings

Ian Bicking ianb at colorstudy.com
Tue Oct 21 17:01:22 EDT 2003


On Tuesday, October 21, 2003, at 03:32 PM, Eron Lloyd wrote:
> Does anyone know of a simple way to truncate string insertions in a 
> ZPT? What
> I'm looking for is basically a replacement for dtml-var's "size" and 
> "etc"
> attributes. I would do it on the MySQL side but that doesn't seem to 
> have
> such a function, either.

Maybe just do it Python-like:

<span tal:condition="python: len(var) > 10" tal:omit-tag="">
   <span tal:replace="python: var[:10]">var</span>...
</span>
<span tal:condition="python: len(var) < 10" tal:omit-tag="">
   <span tal:replace="var">var</span>
</span>



Well, that's not very appealing, is it?  Or a Python Script:

#truncate
#parameters=s, length=10, etc='...'
s = str(s)
if len(s) > length:
     return s[:length] + etc
else:
     return s

<span tal:replace="python: container.truncate(var, 10, 
etc='...(more)...')">var</span>

Really ZPT (TALES really) is painfully in need of easy-to-access 
formatters.  I saw discussions of it long ago in the archives, but is 
there any progress on this?  E.g.:

<span tal:replace="var" tal:format="formatters/truncate">var</span>

Or:

<span tal:replace="var" tal:format="python: 
formatters.truncate(5)">var</span>

Where tal:format operates on the result of tal:replace or tal:content.  
This implies some sort of currying, like:

#truncate
#parameters=length=10, etc='...'
def format(s, length=length, etc=etc):
     if len(str(s)) > length:
         return str(s)[:length] + etc
     else:
         return str(s)
return format

How higher-level functions interact with TALES, I'm not sure... but if 
it's more difficult, it matters much less that the formatters are easy 
to program, compared to being easy to use.  Or maybe this is really 
just the importing problem, because this would be just as good:

<span tal:replace="structure python: formatters.truncate(var, 
10)">var</span>

[I think tal:format would imply structure]  But the current access to 
these sorts of functions through the modules variable is painful at 
best.  And it seems like the functions in PythonScripts.standard are a 
little sparse.

But really the second example isn't so bad, I suppose 
(container.truncate).

--
Ian Bicking | ianb at colorstudy.com | http://blog.ianbicking.org




More information about the ZPT mailing list