我正在创建使用 jinja2 作为模板引擎生成特定文件的脚本。它创建了我期望的文件,除了最后一行。在模板中,我指定了最后一个空行,但是在创建文件时它没有该行。
模板如下所示:
# -*- coding: utf-8 -*-
from openerp import fields, models, api
class {{ class_name }}(models.{{ model_type }}):
"""{{ class_docstring }}"""
_{{ def_type }} = '{{ model }}'
# Here is actually empty line. Note comment does not exist on template. It is just empty line.
所以在这个模板中总共定义了 10 行。但是使用此模板创建的文件将只有 9 行(不会创建最后一行)。
这是预期的行为还是应该按照我的预期创建最后一行?
这里处理渲染的数据和方法:
from jinja2 import Environment, FileSystemLoader
PATH = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_ENVIRONMENT = Environment(
autoescape=True,
loader=FileSystemLoader(os.path.join(PATH, 'templates')),
trim_blocks=False)
...
...
@staticmethod
def render_template(t, context):
# For now it only supports standard templates.
template_filename = TEMPLATE_FILES_MAPPING[t]
return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(
context)
最佳答案
keep_trailing_newline
选项可能是您正在寻找的:
By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline.
您可以将其添加到环境中:
TEMPLATE_ENVIRONMENT = Environment(
...
keep_trailing_newline=True)
关于python-2.7 - jinja2 忽略最后一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40832588/