Tara
Tara

Reputation: 101

template in python

How to write a function render_user which takes one of the tuples returned by userlist and a string template and returns the data substituted into the template, eg:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> render_user(('[email protected]', 'matt rez', ), tpl)
"<a href='mailto:[email protected]>Matt rez</a>"

Any help would be appreciated

Upvotes: 9

Views: 4122

Answers (2)

gavenkoa
gavenkoa

Reputation: 48743

from string import Template
t = Template("${my} + ${your} = 10")
print(t.substitute({"my": 4, "your": 6}))

Upvotes: 4

miku
miku

Reputation: 188014

No urgent need to create a function, if you don't require one:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> s = tpl % ('[email protected]', 'matt rez', )

>>> print s
"<a href='mailto:[email protected]'>matt rez</a>"

If you're on 2.6+ you can alternatively use the new format function along with its mini language:

>>> tpl = "<a href='mailto:{0}'>{1}</a>"
>>> s = tpl.format('[email protected]', 'matt rez')

>>> print s
"<a href='mailto:[email protected]'>matt rez</a>"

Wrapped in a function:

def render_user(userinfo, template="<a href='mailto:{0}'>{1}</a>"):
    """ Renders a HTML link for a given ``userinfo`` tuple;
        tuple contains (email, name) """
    return template.format(userinfo)

# Usage:

userinfo = ('[email protected]', 'matt rez')

print render_user(userinfo)
# same output as above

Extra credit:

Instead of using a normal tuple object try use the more robust and human friendly namedtuple provided by the collections module. It has the same performance characteristics (and memory consumption) as a regular tuple. An short intro into named tuples can be found in this PyCon 2011 Video (fast forward to ~12m): http://blip.tv/file/4883247

Upvotes: 12

Related Questions