【问题标题】:Python text template renderringPython文本模板渲染
【发布时间】:2021-09-15 03:56:43
【问题描述】:

我有一个用 Node.js 实现的应用程序,它具有呈现文本模板的功能:

function render(template, args) {
    // ...
}

render('${ foo.bar }, ${ baz }!', { foo: { bar: 'Hello' }, baz: 'World' });
// Hello, World!

在 Node.js 中,我使用一个流行的库 lodash.template 来实现这一点。

lodash.template('${ foo.bar }, ${ baz }!')({ foo: { bar: 'Hello' }, baz: 'World' });
// Hello, World!

现在我需要将此实现迁移到 Python3。我找到了一个类似的解决方案,它使用了 builin string 模块:

from string import Template

Template('${foo}, ${bar}!').substitute({'foo': 'Hello', 'bar': 'World!'})
# Hello, World!

Template('${foo}, ${bar.baz}!').substitute({'foo': 'Hello', 'bar': { 'baz': 'World!' }})
# ValueError: Invalid placeholder in string

但是,似乎内置 python string.Template 不支持 dot 访问 dict 子属性

用户提供的数据库中已经保存了很多模板,所以现在我无法更新语法规则。

有没有办法解决这个问题?

【问题讨论】:

    标签: javascript python templates


    【解决方案1】:

    Jinja2 模板引擎:

    import jinja2
    
    t = jinja2.Environment(variable_start_string='${', variable_end_string='}').from_string('${foo}, ${bar.baz}!')
    t.render(**{'foo': 'Hello', 'bar': {'baz': 'World'}})
    # Hello, World!
    

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 2011-11-02
      • 2010-11-30
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 2020-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多