不想导入功能齐全的模板引擎可能是有原因的,例如想在资源严重受限的环境中运行代码。如果是这样,用几行代码就可以做到这一点并不难。
以下可以处理模板字符串中标识为 $A 到 $Z 的最多 26 个元素的元组列表,并返回模板扩展列表。
from string import Template
def iterate_template( template, items):
AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
return [ Template(template).safe_substitute(
dict(zip( AZ, elem ))) for elem in items ]
编辑:为了提高效率,我可能应该实例化一次模板并在列表理解中多次使用它:
def iterate_template( template, items):
AZ=[ 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[i:i+1] for i in range(26) ] # ['A','B',... 'Z']
tem = Template(template)
return [ tem.safe_substitute( dict(zip( AZ, elem ))) for elem in items ]
使用示例
>>> table = [('cats','feline'), ('dogs','canine')]
>>> iterate_template('| $A | $B |', table )
['| cats | feline |', '| dogs | canine |']
>>> x=Template('$heading\n$stuff').substitute(
heading='This is a title',
stuff='\n'.join(iterate_template('| $A | $B | $C |',
[('cats','feline'), ('dogs', 'canine', 'pack')] ) ) # slight oops
)
>>> print(x)
This is a title
| cats | feline | $C |
| dogs | canine | pack |