如何使用类似列表的类型来生成带有 string.Template python 的降价?

How can I use a list-like type to generate a markdown with string.Template python?

我有以下模板

from string import Template
myTemplate = '''$heading
| Name | Age |
| ---- |---- |
'''

问题是写模板的时候不知道table会有多少人。所以我想传入一个元组列表,例如:

myTemplate.substitute(...=[("Tom", "23"), ("Bill", "43"), ("Tim", "1")])

如何做到这一点?如果我只是为带有元组的列表添加一个占位符,这将不起作用,因为数据的周围格式将会丢失。

我希望模板捕获格式,希望列表捕获数据并将这两个元素分开。

结果应该是这样的:

| Name | Age |
| ---- |---- |
| Tom  | 23  |
| Bill | 43  |
| Tim  | 1   |

我推荐Mustache。这是一个简单的模板引擎,可以满足您的需求。

可能有一些不想导入功能齐全的模板引擎的原因,例如想要在严肃的 resource-limited 环境中 运行 代码。如果是这样,用几行代码就可以做到这一点。

下面可以处理模板字符串中标识为 $A 到 $Z 的最多 26 个元素的元组列表,以及 returns 模板扩展列表。

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 |