format strings or page tempaltes

Denis S. Otkidach ods at fep.ru
Tue Jul 23 08:06:59 EDT 2002


On Tue, 23 Jul 2002, Jeff Davis wrote:

JD> I am trying to make use of an organized templating system
JD> for web
JD> development. I really just need something simple, so I was
JD> considering
JD> using format strings (just doing "open('mytemplate').read()
JD> % mydict").
JD> The only thing that seems to be lacking for me is the
JD> ability to call a
JD> function with arguments from the template file. For example,
JD> here's what
JD> I'd like to be able to do:
JD>
JD> <html>
JD> ....
JD> %(myfunction("foo"))s
JD> .....
JD> </html>

import sys

class EvalDict:

    def __init__(self, globals=None, locals=None):
        if globals is None:
            globals = sys._getframe(1).f_globals
        self.globals = globals
        if locals is None:
            locals = sys._getframe(1).f_locals
        self.locals = locals

    def __getitem__(self, key):
        key = key % self
        return eval(key, self.globals, self.locals)


>>> def myFunc(arg):
...     return '!%s!' % arg
...
>>> print 'Template with %(myFunc("My argument"))s call' % EvalDict()
Template with !My argument! call

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]
http://diveinto.python.ru/ [ru]






More information about the Python-list mailing list