在 python 中我可以使用一个模板
from string import Template
templ = Template('hello ${name}')
print templ.substitute(name='world')
如何在模板中定义默认值? 并在没有任何值的情况下调用模板。
print templ.substitute()
编辑
当我不带参数调用时获取默认值,示例
print templ.substitute()
>> hello name
最佳答案
Template.substitute
方法采用 mapping
argument in addition to keyword arguments .关键字参数覆盖 mapping
位置参数提供的参数,这使得 mapping
成为实现默认值的自然方式,无需子类化:
from string import Template
defaults = { "name": "default" }
templ = Template('hello ${name}')
print templ.substitute(defaults) # prints hello default
print templ.substitute(defaults, name="world") # prints hello world
这也适用于 safe_substitute
:
print templ.safe_substitute() # prints hello ${name}
print templ.safe_substitute(defaults) # prints hello default
print templ.safe_substitute(defaults, name="world") # prints hello world
如果您绝对坚持不向 substitute
传递任何参数,您可以子类化模板:
class DefaultTemplate(Template):
def __init__(self, template, default):
self.default = default
super(DefaultTemplate, self).__init__(template)
def mapping(self, mapping):
default_mapping = self.default.copy()
default_mapping.update(mapping)
return default_mapping
def substitute(self, mapping=None, **kws):
return super(DefaultTemplate, self).substitute(self.mapping(mapping or {}), **kws)
def substitute(self, mapping=None, **kws):
return super(DefaultTemplate, self).safe_substitute(self.mapping(mapping or {}), **kws)
然后像这样使用它:
DefaultTemplate({ "name": "default" }).substitute()
尽管我发现这比仅传递一个默认为 substitute
的 mapping
更不明确且可读性较差。
关于具有默认值的python模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51160798/