Looking for very light weight template library (not framework)
Duncan Booth
duncan.booth at invalid.invalid
Fri Mar 7 03:46:43 EST 2008
"Malcolm Greene" <python at bdurham.com> wrote:
> New to Python and looking for a template library that allows Python
> expressions embedded in strings to be evaluated in place. In other
words
> something more powerful than the basic "%(variable)s" or "$variable"
> (Template) capabilities.
>
> I know that some of the web frameworks support this type of template
> capability but I don't need a web framework, just a library that
> supports embedded expression evaluation.
You could try using the Template class:
>>> from string import Template
>>> class EvalTemplate(Template):
idpattern = '[^{}]+'
>>> class EvalDict(dict):
def __getitem__(self, name):
if name in self:
return dict.__getitem__(self, name)
return eval(name, globals(), self)
>>> class Invoice:
def __init__(self, total):
self.total = total
>>> i = Invoice(42)
>>> template = EvalTemplate("The total cost is ${invoice.total}")
>>> template.substitute(EvalDict(invoice=i))
'The total cost is 42'
The usual caveats about using 'eval' apply (maybe it should be called
EvilDict), and I'm sure you could override substitute/safe_substitute to
construct the EvalDict transparently.
More information about the Python-list
mailing list