[Web-SIG] htmlgen

Ian Bicking ianb at colorstudy.com
Thu Oct 30 13:11:08 EST 2003


On Thursday, October 30, 2003, at 11:54 AM, Gregory (Grisha) Trubetskoy 
wrote:
> It comes in handy in various HTML formatting, e.g. let's say we have a
> menu, and you want one item highlighted:
>
> HTML = """
>   <a href="home" %(home)s >Home</a><br>
>   <a href="products" %(prod)s >Products</a><br>
>   <a href="about" %(about)s >About</a><br>
> """
>
> To highlight home you'd have to do something like:
>
> HTML % {'home' : 'class="highlighted"', 'prod':'', 'about':''}
>
> But it's nice to not have to list every menu option (less typing, and
> more importantly, you can change the template without having to fix the
> code), something functionally equivalent to:
>
> HTML % {'home' : 'class="highlighted"'}
>
> (this would raise key error)

This would solve this particular problem:

class EmptyStringDict(dict):
     def __getitem__(self, item):
         try:
             return dict.__getitem__(self, item)
         except KeyError:
             return ''

You might add a test for None as well, and replace None with '' (which 
is what I always want in these sorts of situations).  A more structured 
description can work even better, though.  Something like:

classes = {'home': 'highlighted'}
html(
     html.a(href="home", class_=classes.get('home'))('Home'), html.br(),
     html.a(href="products", 
class_=classes.get('products'))('Produccts'), html.br(),
     html.a(href="about", class_=classes.get('about'))('About'), 
html.br(),
     )

In this example, any attribute with a value None will simply be 
excluded.  (Perhaps there should also be a way to indicate an attribute 
with no value, like "checked" -- I've used None for that and a special 
object for exclude before, or that could be reversed)

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




More information about the Web-SIG mailing list