n00b question: Possible to pass lists to a Template class?

MRAB google at mrabarnett.plus.com
Wed May 13 19:10:35 EDT 2009


Rhodri James wrote:
> On Wed, 13 May 2009 17:22:32 +0100, Wells <wells at submute.net> wrote:
> 
>> On May 13, 11:14 am, Wells <we... at submute.net> wrote:
>>> Is it possible to pass a list to the Template.substitute method and
>>> use that in the template, like so..
>>>
>>> g = string.Template(gametemplate)
>>> print g.substitute(recap = "none", winner = game["winner"], loser =
>>> game["loser"])
>>>
>>> Then in the template...
>>>
>>> <b>winner.team
>>>
>>> Where winner.team would be the value of game["winner"]["team"].
>>>
>>> Thanks!
>>
>> Sorry, I meant dicts, not lists. Like I said, n00b question.
> 
> Basically, no.  Substituted values are effectively put into the
> template with '%s' substitution, so you'll just get a string
> representation of your dictionary.  You could play around with
> defining your own custom Template class, but it's probably not
> worth the effort.
> 
The closest you can get is to pass a dict:

 >>> import string
 >>> s = string.Template("winner is $winner, loser is $loser")
 >>> s.substitute(winner="w", loser="l")
'winner is w, loser is l'
 >>> d = {"winner": "w", "loser": "l"}
 >>> s.substitute(d)
'winner is w, loser is l'




More information about the Python-list mailing list