On Mar 6, 8:56 pm, "Malcolm Greene" <[EMAIL PROTECTED]> 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. > > Use case: > > myOutput = """\ > > The total cost is {{invoice.total}}. > > This order will be shipped to {{invoice.contact}} at the following > address: > > {{invoice.address}} > > This order was generated at {{some date/time expression}} > """ > > Any suggestions appreciated.
You could do something like this with a single function. For instance: import re def apply_template(text,env): def eval_in_env(m): return str(eval(m.group(1),env)) return re.sub(r"{{(.*?)}}",eval_in_env,text) Where env is a dict with the variables you want to evaluate (locals() could be a good choice for this). Standard warning about usage of eval: don't use this with untrusted input or Bad Things can happen. Carl Banks -- http://mail.python.org/mailman/listinfo/python-list