本文整理匯總了Python中jinja2.Template.format方法的典型用法代碼示例。如果您正苦於以下問題:Python Template.format方法的具體用法?Python Template.format怎麽用?Python Template.format使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類jinja2.Template
的用法示例。
在下文中一共展示了Template.format方法的1個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: from_template
# 需要導入模塊: from jinja2 import Template [as 別名]
# 或者: from jinja2.Template import format [as 別名]
def from_template(template, destination, values, jinja2=False):
"""
Generate a `destination` file from a `template` file filled with `values`, method: string.format or jinja2!
**Example usage**
>>> open('config.template', 'w', 'utf-8').write('{{username={user}; password={pass}}}')
The behavior when all keys are given (and even more):
>>> from_template('config.template', 'config', {'user': 'tabby', 'pass': 'miaow', 'other': 10})
>>> print(open('config', 'r', 'utf-8').read())
{username=tabby; password=miaow}
The behavior if a value for a key is missing:
>>> from_template('config.template', 'config', {'pass': 'miaow', 'other': 10}) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
KeyError: ...'user'
>>> print(open('config', 'r', 'utf-8').read())
<BLANKLINE>
>>> os.remove('config.template')
>>> os.remove('config')
"""
with open(template, 'r', 'utf-8') as template_file:
with open(destination, 'w', 'utf-8') as destination_file:
content = template_file.read()
if jinja2:
from jinja2 import Template
content = Template(content).render(**values)
else:
content = content.format(**values)
destination_file.write(content)