Reputation: 21168
I'm creating script that generates specific files using jinja2 as template engine. It creates file I expect, except for the last line. In template I have specified last empty line, but when file is created it does not have that line.
Template looks like this:
# -*- 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.
So in total there are 10 lines defined in this template. But file that is created using this template will only have 9 lines (that last line will not be created).
Is this expected behavior or it should create me that last line as I am expecting?
Here data and methods that handle rendering:
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)
Upvotes: 7
Views: 3844
Reputation: 31
Another option is to finish the template with two newlines and let jinja2 strip one of them:
File contents
File contents
...
# Actual empty line (without this comment) which is kept by jinja2
# Actual empty line (without this comment) which is stripped by jinja2
Upvotes: 0
Reputation: 1066
The keep_trailing_newline
option may be what you're looking for:
By default, Jinja2 also removes trailing newlines. To keep single trailing newlines, configure Jinja to keep_trailing_newline.
You can add it to the environment:
TEMPLATE_ENVIRONMENT = Environment(
...
keep_trailing_newline=True)
Upvotes: 11