[ZPT] Added Python code blocks to ZPT

Ian Bicking ianb at colorstudy.com
Tue May 17 15:00:11 EDT 2005


Well, ZPT is pretty slow moving these days, but there's a feature that 
I'd be interested in.  It's inspired by Kid 
(http://lesscode.org/projects/kid/), which is very similar to ZPT.  In 
it, you can have Python code:

<?python
   ...
?>

But unlike PHP, ASP, and family, the Python code can't produce output 
and must be self-contained.  This allows for a nice continuum as code 
becomes more complex; you can start out with a normal tal expression, 
move to a python: tal expression, and then move things into a header, 
and finally move things out into an external script.

For example, imagine a select box:

<select name="state">
  <option tal:repeat="state options/states"
   tal:attributes="href state/code;
     selected python: test(state['code'] == request.get('state',
         options.get('state'), 'selected')">
    <span tal:replace="state/code"/>
    <span tal:condition="state/long_name">:
     <span tal:replace="state/long_name"/></span>
  </option>
</select>

Brutal, eh?  But we've probably all been there.  With a PI:

<?python
state_sel = []
for state in options['states']:
     state_data = {}
     if state['code'] == request.get('state', options.get('state')):
         state_data['selected'] = 'selected'
     state_data['description'] = state_data['code'] = state['code']
     if state['long_name']:
         state_data['description'] += ': ' + state['long_name']
     state_sel.append(state_data)
?>
<select name="state">
  <option tal:repeat="state state_sel"
   tal:attributes="value state/code selected state/selected | nothing"
   tal:content="state/description">state</option>
</select>

It's not any shorter, but it sure is easier to write, and keeps the 
markup fairly clean.

Of course, in most environments there's ways to move this code elsewhere 
-- into an external function or into the code that calls this template. 
  But that turns what's actually a very localized bit of display-related 
code into something else.  This doesn't actually *belong* in the 
"controller"; the Python code is clearly part of the view.  But it's 
also horribly ugly when put into the markup.

I think it's actually really good for ZPT's ideal of being friendly to 
people with different roles -- the markup becomes simple enough for 
someone who knows only HTML, and for those middling people (of which I 
think there are many) who would be comfortable with Python but aren't 
necessarily comfortable with adding code to a controller or a Python 
script (code which probably has much different duties), it gives them an 
easy transitional area.

Anyway, I think it's a nice idea, and would fit well into ZPT.

(I'd also love if ZPT did ${expr} substitution like Kid, but that's a 
different issue)

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


More information about the ZPT mailing list