【问题标题】:How can I use a list-like type to generate a markdown with string.Template python?如何使用类似列表的类型通过 string.Template python 生成降价?
【发布时间】:2016-04-08 01:05:49
【问题描述】:

我有以下模板

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

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

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

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

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

结果应该如下:

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

【问题讨论】:

    标签: python python-2.7 markdown


    【解决方案1】:

    不想导入功能齐全的模板引擎可能是有原因的,例如想在资源严重受限的环境中运行代码。如果是这样,用几行代码就可以做到这一点并不难。

    以下可以处理模板字符串中标识为 $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 |
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 似乎python没有为此内置任何东西而不是手动执行它,因此拥有一个更完整的系统会更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-11
      • 2010-10-29
      • 2022-07-13
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多