【问题标题】:light weight template engine for pythonpython的轻量级模板引擎
【发布时间】:2010-12-10 05:53:00
【问题描述】:

这是 Python 中最简单、轻量级的 html 模板引擎,我可以使用它来生成自定义的电子邮件通讯。

【问题讨论】:

    标签: python templating


    【解决方案1】:

    对于一个非常小的模板任务,Python 本身并没有那么糟糕。示例:

    def dynamic_text(name, food):
        return """
        Dear %(name)s,
        We're glad to hear that you like %(food)s and we'll be sending you some more soon.
        """ % {'name':name, 'food':food}
    

    从这个意义上说,您可以在 Python 中使用字符串格式化来进行简单的模板化。这几乎是轻量级的。

    如果您想更深入一点,Jinja2 在许多人看来是最“设计师友好”(阅读:简单)的模板引擎。

    你也可以看看 Mako 和 Genshi。最终,选择权在您手中(具有您喜欢的功能并与您的系统完美集成的功能)。

    【讨论】:

    • 我同意,很多时候 Python 的格式化工具正是我们所需要的。您可以执行"Hello {foo}".format(foo="World") 之类的操作。还要考虑一下,Python string 模块:docs.python.org/library/string.html#template-strings 但是一旦您开始在模板中需要一些条件或迭代逻辑,您将需要其他答案中建议的更实质性的东西。
    【解决方案2】:

    string.Template 有什么问题吗?这是在标准 Python 发行版中,由 PEP 292 覆盖:

    from string import Template
    
    form=Template('''Dear $john,
    
    I am sorry to imform you, $john, but you will not be my husband
    when you return from the $theater war. So sorry about that. Your
    $action has caused me to reconsider.
    
    Yours [NOT!!] forever,
    
    Becky
    
    ''')
    
    first={'john':'Joe','theater':'Afgan','action':'love'}
    second={'john':'Robert','theater':'Iraq','action':'kiss'}
    third={'john':'Jose','theater':'Korean','action':'discussion'}
    
    print form.substitute(first)
    print form.substitute(second)
    print form.substitute(third)
    

    【讨论】:

    • str.format() 比 string.Template 强大得多,但同样简单。
    【解决方案3】:

    我认为Werkzeug Mini Templates 非常适合。

    这是 Github 上的 the source code

    【讨论】:

    • 注意:两个链接自 Sun 2017-04-02T00:41:01 起无效
    【解决方案4】:

    在 Google 中搜索 tiny template Python 出现了 Titen,其源代码只有 5.5 kB。 Titen 可以对列表进行迭代,而内置的 str.format 不能。

    Mako 声称是轻量级的,但与 Titen 相比,它相对较胖 (>200 kB)。 Jinja2 和 Django 模板也超过 100 kB。

    【讨论】:

      【解决方案5】:

      试试python-micro-template:

      https://github.com/diyism/python-micro-template

      用法示例(kivy):

      import python_micro_template
      ...
      kvml=open('example_kivy_scrollview.kvml', 'r').read()
      kvml=python_micro_template.tpl.parse(kvml)
      grid=Builder.load_string(kvml)
      ...
      

      模板示例(kvml):

      <:for i in range(30):#{#:>
      Button:
          text: '<:=i:><:for j in range(6):#{#:><:=j:><:#}#:>'
          size: 480, 40
          size_hint: None, None
      <:#}#:>
      

      【讨论】:

        猜你喜欢
        • 2011-02-06
        • 1970-01-01
        • 1970-01-01
        • 2011-02-28
        • 2013-01-06
        • 1970-01-01
        • 2011-02-26
        • 2011-03-26
        • 1970-01-01
        相关资源
        最近更新 更多