[mod_python] kid template decorator [prev: Current Working Directory not set?]

Nicolas Lehuen nicolas.lehuen at gmail.com
Sat Jan 28 04:50:41 EST 2006


Hi,

I'm using something similar with a custom-made templating system
(which looks a bit like Velocity).

I have used req.filename rather than __file__ to get the path of the
file requested, because the decorator function is stored in a separate
library module, which means that __file__ always return the path to
the library module and not the path to the published module.

One could also use stack inspection to get the proper path but
req.filename is quite reliable as far as the publisher is concerned.

Just a small detail : you can test whether a path is absolute or
relative thanks to os.path.isabs, so you can only provide one path
parameter and let Python decide of its relativeness.

Regards,
Nicolas

2006/1/28, Sean Jamieson <sean at barriescene.com>:
> OK, so here is my decorator solution:
>
> # @template decorator
> def template( relpath = 'templates', template=None, abspath=None ):
>     def decor( func ):
>         if abspath:
>             path = abspath
>         else:
>             path = os.path.join( os.path.dirname( __file__ ), relpath )
>         if template:
>             path = os.path.join( path, template )
>         else:
>             path = os.path.join( path, '%s_%s.kid' %
> (func.__module__.split('.')[-1], func.func_name) )
>         def template_wrapper( *args, **kwargs ):
>             kwargs['req'].content_type = 'text/html'
>             values = func( *args, **kwargs )
>             return Template( file=path, **values )
>         # just so debug output makes sense
>         template_wrapper.func_name = '%s(%s)' % (
> template_wrapper.func_name, func.func_name )
>         return template_wrapper
>     return decor
>
> @template()
> def index( req ):
>     title = 'some title'
>     message = 'Keep it simple, stupid.'
>     return vars()
>
> ... or something like that...
>
> Comments?
>
> Sean



More information about the Mod_python mailing list