简体   繁体   English

python中的模板

[英]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: 如何编写一个函数render_user,它接受userlist返回的一个元组和一个字符串模板,并返回替换到模板中的数据,例如:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> render_user(('matt.rez@where.com', 'matt rez', ), tpl)
"<a href='mailto:matt.rez@where.com>Matt rez</a>"

Any help would be appreciated 任何帮助,将不胜感激

No urgent need to create a function, if you don't require one: 如果您不需要,不需要创建函数:

>>> tpl = "<a href='mailto:%s'>%s</a>"
>>> s = tpl % ('matt.rez@where.com', 'matt rez', )

>>> print s
"<a href='mailto:matt.rez@where.com'>matt rez</a>"

If you're on 2.6+ you can alternatively use the new format function along with its mini language: 如果您使用2.6+,您可以使用新的format功能及其迷你语言:

>>> tpl = "<a href='mailto:{0}'>{1}</a>"
>>> s = tpl.format('matt.rez@where.com', 'matt rez')

>>> print s
"<a href='mailto:matt.rez@where.com'>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 = ('matt.rez@where.com', '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. 不要使用普通的tuple对象,而是尝试使用collections模块提供的更健壮,更友好的namedtuple tuple It has the same performance characteristics (and memory consumption) as a regular tuple . 它具有与常规tuple相同的性能特征(和内存消耗)。 An short intro into named tuples can be found in this PyCon 2011 Video (fast forward to ~12m): http://blip.tv/file/4883247 在这个PyCon 2011视频中可以找到命名元组的简短介绍(快进到~12m): http//blip.tv/file/4883247

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM